我有一个简单的查询,在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
如何使用预准备语句执行set操作?
更新:
按照你的建议后我想出了这个
$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
Taraam。工作正常。
答案 0 :(得分:2)
类似的东西:
$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();