php - 如何将数组中包含的参数列表传递给bind_param?

标签 php mysql mysqli

使用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/

相关文章:

php - 刷新或打开页面会将空数据插入我的数据库! PHP, 来自

php - 如何将代码中的条件调整集中到不同页面上?

php - 获取在 PHP 函数中声明的变量的值

php - 使用 PHP 编辑 Windows 安装程序 (.msi)

php - 如何检索数组中与查询关联的其他值?

PHP创建下拉菜单,插入数据库

php - CakePHP 中的存储过程错误

php - 客户端断开连接后 CSimpleSocket 失败

php - laravel 4.2 对复杂查询进行分页

mysql - 时间戳差异并单独获取小时、分钟和秒