动态生成mysqli bind_param用于" WHERE IN"使用php 5.3+的语句

时间:2014-06-30 16:34:46

标签: php mysqli prepared-statement

这个问题依赖于answer about using call_user_func_array来动态生成bind_param语句,并且在php手册上有a user posting关于必须将引用的项传递给bind_param语句。但是,问题仍然存在:

  

PHP警告:mysqli_stmt :: bind_param():变量数没有   匹配

中预准备语句中的参数数量

以下是代码:

$error_id_list = implode(',', array_fill(0, count($error_ids), '?'));
$type=""; for ($i=0; $i<count($error_ids); $i++){$type .= "i";}
$query = "SELECT `id`, `question`, `multi_1`, `multi_2`, `multi_3`, `multi_4` FROM `student_exam` WHERE `id` IN ('".$error_id_list."') ORDER BY RAND() LIMIT 0, 5";
$result = $mysqli->prepare($query);
if($result === FALSE)
    die($result->error);
array_unshift($error_ids, $type);
call_user_func_array(array($result, 'bind_param'), refValues($error_ids));
$result->execute();
$result->store_result();
$result->bind_result($id,$question,$multi1,$multi2,$multi3,$multi4);

while($result->fetch()){
    $output;
}
$result->free_result();

return $output;

谢谢!

1 个答案:

答案 0 :(得分:0)

错误是微不足道的,SQL语句中的问号不需要被引号包围(尽管StackOverflow上的其他几个答案都使用引号)。

$error_id_list = implode(',', array_fill(0, count($error_ids), '?'));
$type=""; for ($i=0; $i<count($error_ids); $i++){$type .= "i";}
$query = "SELECT `id`, `question`, `multi_1`, `multi_2`, `multi_3`, `multi_4` FROM 
  `student_exam` WHERE `id` IN ('".$error_id_list."') ORDER BY RAND() LIMIT 0, 5";
                                ^^--- no quotes --^^
$result = $mysqli->prepare($query);
if($result === FALSE)
    die($result->error);
array_unshift($error_ids, $type);
call_user_func_array(array($result, 'bind_param'), refValues($error_ids));
$result->execute();
$result->store_result();
$result->bind_result($id,$question,$multi1,$multi2,$multi3,$multi4);

while($result->fetch()){
    $output;
}
$result->free_result();

return $output;