views:

28

answers:

3

Imagine I have the following SQL query:

SELECT id,name FROM user WHERE id IN ('id1','id2','id3')

Now imagine I need the array of ids to be supplied by PHP. So I have something like this:

$idList = array('id1','id2','id3');
$query = "SELECT id,name FROM user WHERE id IN (?)";
$stmt = $db->prepare($query);
$stmt->bind_param(/*Something*/);

What can I replace /*Something*/ with to get the same results as the original query? Or do I need to put in 3 question marks in the query format? The only reason I don't want to do that is because the number of question marks is variable, so I would have to build the query string manually.

+1  A: 

implode would be the simplest solution

$idList = array('id1','id2','id3');
$query = "SELECT id,name FROM user WHERE id IN (?)";
$stmt = $db->prepare($query);
$_param = is_array($idList) ? implode(',',$idList) : $idList;
$stmt->bind_param(1, $_param);
maggie
Tried it, no luck
Ed Marty
This won't properly quote/escape your list, which defeats the purpose of parameterization!
Daniel Vandersluis
+1  A: 

Can I bind multiple values as a single parameter using MYSQLI and PHP?

No you cannot.

For your situation, you should build the query string programmatically. If you are guaranteed it will always be three values, you could add three markers to the SQL then bind via looping over the array.

webbiedave
Which means I suppose that I will have to use call_user_func_array to actually call the bind_param method as well
Ed Marty
You could just loop through the array.
webbiedave
Could you elaborate on that? How? I've only ever bound parameters all at once.
Ed Marty
+2  A: 

You can use PHP to write out the placeholders ? using str_repeat(), and then just bind_param all your params in a loop.

Just be careful of the trailing comma that str_repeat will return. Either rtrim() it or instead use array_fill() to create an array of repeating placeholders and then join() those to create your placeholders string.

$arrPlaceholders = array_fill(0, count($idList), '?') ;
$strPlaceholders = join(', ', $arrPlaceholders) ;

Then your query can be:

$query = "SELECT id,name FROM user WHERE id IN ($strPlaceholders)";

And you can bind your parameters in a loop.

Fanis
Can I use a loop to bind parameters with MYSQLI? How? When looking at mysqli_stmt_bind_param I see this: "The number of variables and length of string types must match the parameters in the statement."
Ed Marty
@Ed that's actually an interesting issue I hadn't noticed straight away, as I don't use mysqli. It does look like `bind_param()` needs to include all the parameters in that one call, so a loop will not work. Looking at the manual, some people have thought of some smart solutions to it: http://www.php.net/manual/en/mysqli-stmt.bind-param.php#89097 and the one below it that suggests `call_user_func_array()`
Fanis