我有以下内容:
<?php
$array = join(',', $ids); // this prints 3,4,6,7,8
$stmt = $cxn->prepare('SELECT * FROM comments WHERE id IN (?)');
$stmt->bind_param('i', $array);
$stmt->execute();
?>
但是,当我打印结果时,它只会显示第一个ID(3
)而不是其他ID的注释。怎么了?
答案 0 :(得分:1)
我相信为了按预期工作,你必须直接将值替换为字符串:
$idString = '';
foreach($ids as $id) {
$idString .= $id . ',';
}
$idString = substr($idString, 0, -1);
$stmt = $cxn->prepare("SELECT * FROM comments WHERE id IN (".$idstring.")");
$stmt->execute();
不幸的是,这可以让你打开SQL注入攻击。
答案 1 :(得分:0)
$arrayCount = count($ids);
$binders = array_fill(0, $arrayCount, '?');
// Create an array of references to the values we want to bind
$bindValues = array();
foreach($ids as $key => $id)
$bindValues[$keys] = &$ids[$key];
// Build SQL statement with the necessary number of bind placeholders
$stmt = $cxn->prepare(
'SELECT * FROM comments WHERE id IN (' . implode(',', $binders) . ')'
);
// Bind each value (has to be done by reference)
call_user_func_array(array($stmt, "bind_param"), $bindValues));
$stmt->execute();
答案 2 :(得分:-1)
将它们绑定到一个字符串。
$idString = '';
foreach($ids as $id) {
$idString .= $id . ',';
}
$idString = substr($idString, 0, -1);
$stmt = $cxn->prepare('SELECT * FROM comments WHERE id IN (?)');
$stmt->bind_param('s', $idString);
$stmt->execute();