問題描述
根據http://us2.php.net/manual/en/mysqli-stmt.bind-param.php,不同的類型是:
i corresponding variable has type integer
d corresponding variable has type double
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 (?)")
在哪里?將是一個 id 列表.可能有一項或多項:
Where ? would be a list of ids. There could be one or more items:
$ids = "3,4,78";
->bind_param('s',$ids);
這可能嗎?
我想使用準備好的語句,因為它將在循環中執行.
I'd like to use prepared statements because it will be executed in a loop.
推薦答案
如果你有一個大小不同的變量列表,你想綁定到 IN
語句的每個調用,最簡單的方法是以編程方式生成 SQL 字符串并使用循環來綁定變量:
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;
}
如果你喜歡call_user_func_array
,你可以使用動態方法調用并且沒有循環.
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;
}
這篇關于php mysqli WHERE IN (?,?,? ...)的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!