I have a table with multiple columns in it, one of which, labeled 'ID'
, contains a unique number. I am sending a list of values to pull to a server-side php script that uses a prepared statement to make the pull. Through some research I found that I believe I am looking for IN
inside of my statement. I get how to hardcode a list in to the statement, such as: SELECT * FROM spotzz WHERE ID IN (465, 732, 219)
or something along those lines, but my confusion comes from the prepared statement. I need a ?
for every value I'm passing to the statement, but if the length of the list is not always the same, how do I do this?
You can dynamically generate the prepared statement string based on how many values are in your array:
$values = [1,2,3,4];
$sql = "SELECT * FROM spotzz WHERE `ID` IN (" .
// array_fill() creates an array with as many '?' as there are
// elements in $values. implodes() glues the new array elems with a ","
implode(',', array_fill(0,count($values),'?')) .
")";
echo $sql; // SELECT * FROM spotzz WHERE `ID` IN (?,?,?,?)