php - 使用集合操作时准备好的语句
问题描述
我有一个在 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
塔兰。工作正常。
解决方案
就像是:
$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();
推荐阅读
- reactjs - React Native Background Timer 在 x 时间后执行操作
- python - Why won't my tkinter window move further than 1 pixel?
- tfs - MSBuild is not installed on TFS controller when I installed VS 2017
- javascript - 如何使用 Javascript 从数据库中显示网站上的图像?
- ios - iOS 应用程序和地理编码的 Google Maps API 密钥限制
- typescript - Angular 中的模型
- html - 使用 css 选择器 jsoup 解析 html
- php - 如何使用 php 从 .ini 文件中删除部分
- typescript - 在 Yarn 工作区中使用 Typescript 引用时如何添加自定义类型定义?
- python - 如何增加散景中组标签之间的空间