首页 > 解决方案 > 使用集合操作时准备好的语句

问题描述

我有一个在 PHP 脚本中不太容易执行的简单查询:

SELECT `title` from `MY_TABLE` WHERE id in (30,32,33,44)

通常我使用准备好的语句执行 sql 查询。我放置了一堆?而不是绑定参数。这次括号中的数字是我从用户那里得到的一组数据。

我试过这个,但它不起作用:

$ids = [30,32,33,44];
$stmt = $mysqli->prepare("

SELECT `title` from `MY_TABLE` WHERE id in (?)

");
// $stmt->bind_param();
$stmt->bind_param("i",$ids);
$stmt->execute();
$stmt->bind_result($title);
$stmt->store_result();
//fetch

如何使用准备好的语句执行集合操作?

更新:

听从你的建议后,我想出了这个

$ids = [30,32,33,44];
$questionMarks  = rtrim(str_repeat('?,',count($ids)),", ");
$parameters = str_repeat('i',count($ids));
echo $questionMarks."<br>";
echo $parameters."<br>";
$stmt = $mysqli->prepare("

SELECT `title` from `MY_TABLE` WHERE id in (".$questionMarks.")

");

$scene_names = [];
$stmt->bind_param($parameters, $ids); //error here
$stmt->execute();
$stmt->bind_result($title);
$stmt->store_result();

我仍然收到错误消息。这次它说:

Number of elements in type definition string doesn't match number of bind variables

我不确定为什么它认为元素的数量(在这种情况下是什么元素?)是错误的。

更新 2:

代替:

$stmt->bind_param($parameters, $ids); //error here

我用了:

$stmt->bind_param($parameters, ...$ids); //error gone

塔兰。工作正常。

标签: phpmysqli

解决方案


就像是:

$ids = [30,32,33,44];
$types = array();
foreach($ids as $i){
    array_push($types,'i');
}
$params = array_merge($ids,$types);
$sqlIN  = str_repeat('?,',count($ids));
$sqlIN  = rtrim($sqlIN, ',');

//Value of $sqlIN now looks like ?,?,?,?

$sql = "SELECT title from MY_TABLE WHERE id IN ($sqlIN)";
$stmt = $mysqli->prepare($sql);
call_user_func_array(array($stmt, 'bind_param'), $params);
$stmt->execute();
$stmt->bind_result($id);
$stmt->store_result();

推荐阅读