php mysqli WHERE IN (?,?,? ...) [duplicate]
According to http://us2.php.net/manual/en/mysqli-stmt.bind-param.php, the different types are:
i corresponding variable has type integer
d corresponding variable has type dou开发者_C百科ble
s corresponding variable has type string
b corresponding variable is a blob and will be sent in packets
However, how can you handle this:
->prepare("SELECT blabla FROM foo WHERE id IN (?)")
Where ? would be a list of ids. There could be one or more items:
$ids = "3,4,78";
->bind_param('s',$ids);
Is that possible?
I'd like to use prepared statements because it will be executed in a loop.
The proper syntax would be
->prepare("SELECT blabla FROM foo WHERE id IN (?, ?, ?)")
for 3 items in that array, for example. You would then have to bind each of those items individually using bind_param()
.
If you don't have a size guarantee on the array, you'll have to write a couple helper functions to generate your SQL with the proper number of "?"'s and bind statements.
If you have a list of variables that differs in size every call that you wanto to bind to an IN
-statement, the most simple way would be to generate the SQL string programatically and use a loop to bind the variables:
/**
* @param array $values
* @param mysqli $db
* @return mysqli_stmt
*/
function bindInValues(array $values, mysqli $db)
{
$sql = sprintf('SELECT blabla FROM foo WHERE id IN (%s)',
implode(', ', array_fill(0, count($values), '?'))
);
$stmt = $db->prepare($sql);
foreach ($values as $value) {
$stmt->bind_param('s', $value);
}
return $stmt;
}
If you like call_user_func_array
you can use dynamic method invocation and go along without a loop.
/**
* @param array $values
* @param mysqli $db
* @return mysqli_stmt
*/
function bindInValues(array $values, mysqli $db)
{
$sql = sprintf('SELECT blabla FROM foo WHERE id IN (%s)',
implode(', ', array_fill(0, count($values), '?'))
);
$stmt = $db->prepare($sql);
array_unshift($values, implode('', array_fill(0, count($values), 's')));
call_user_func_array(array($stmt, 'bind_param'), $values);
return $stmt;
}
What about doing this:
$sql = sprintf("SELECT blabla FROM foo WHERE id IN(%s) ", $ids);
$stmt = $mysqli->prepare($sql);
if (!$stmt) {
$this->throwException();
}
if (!$stmt->execute()) {
$this->throwException();
}
If it is not good, please tell me why so I can learn from my errors. Thanks!
I think I found the answer to my question:
->prepare("SELECT stuff FROM table_name WHERE id IN (?)");
$itemList = implode(',',$items);
$children->bind_param('s',$itemList);
Seems to be working fine when using a string with coma-separated values. I'm still checking if the results are really accurate ...
精彩评论