使用MySQLi我想要准备、执行带有 IN
的 SQL 语句并从中获取结果函数,例如:
SELECT id FROM records WHERE isbn IN ( 'aaa', 'bbb', 'ccc' );
用于 IN
的参数实际上是动态的,因此它们将位于一个数组中,每次运行的长度都不同。
对于一次运行,假设数组是:
$list = array('aaa', 'bbb', 'ccc');
因此准备好的语句必须如下所示,带有三个问号:
SELECT id FROM records WHERE isbn IN ( ?, ?, ? );
这是我所拥有的:
$question_marks = str_repeat('?, ', count($list));
$question_marks = preg_replace('/, $/', '', $question_marks);
$stmt = $linkID->prepare("SELECT id FROM records WHERE isbn IN ($question_marks)");
$types = str_repeat('s', count($list));
$stmt->bind_param($types, $list); // this is not working (error below)
我得到的错误是:
mysqli_stmt::bind_param(): Number of elements in type definition string doesn't match number of bind variables
如何将数组中包含的参数列表传递给 bind_param ?
最佳答案
使用 PHP 5.6,您可以在 unpacking Operator 的帮助下轻松完成此操作。 (...$var
) 并使用 get_result()而不是bind_result() .
$stmt->bind_param($types, ...$list);
$stmt->get_result();
关于php - 如何将数组中包含的参数列表传递给bind_param?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49583204/