MySQLi 将参数与 IN 数组绑定 [英] MySQLi Bind Param with an array for IN
问题描述
我试图将一个数组作为 IN 变量传递给 $stmt->bind_param
.我该怎么做?
I am trying to pass an array to $stmt->bind_param
for as an IN variable. How can I do this?
$values = array('a','b','c','d');
$values = '"' . implode('","', $values) . '"';
$stmt->prepare('SELECT value1, value2 FROM table1 WHERE value3 IN (?)');
$stmt->bind_param('s', $values);
我无法让它为我的生活工作.有什么想法吗?上面的代码只是一个示例.
I can't get it to work for the life of me. Any thoughts? The above code is just a sample.
推荐答案
在这种情况下,这样做是不合适的.您正在构建实际的 SQL(这就是逗号和引号),并将其作为参数传入.它基本上是对 value3 IN ('...')
求值,其中 ...
是 $values
的全部.
This is a scenario where doing it this way is inappropriate. You're constructing actual SQL (that's what the commas and quotes are), and passing it in as a parameter. It's basically evaluating to value3 IN ('...')
where ...
is the entirety of $values
.
关于引号的说法也很好.MySQL 使用单引号.
Also that's a good call about the quotes. MySQL uses single quotes.
您需要单独使用字符串连接来构建 SQL,或者使用多个参数.
You'll need to either build the SQL using string concatenation alone, or use more than one parameter.
编辑
举个例子:
$values = array('a','b','c','d');
$values = "'" . implode("','", $values) . "'";
$stmt->prepare('SELECT value1, value2 FROM table1 WHERE value3 IN (' . $values . ')');
这篇关于MySQLi 将参数与 IN 数组绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!