简体   繁体   中英

Dynamically generating mysqli bind_param for “WHERE IN” statements using php 5.3+

This question relies on an answer about using call_user_func_array to dynamically generate bind_param statements, and a user posting on the php manual about having to pass referenced items to bind_param statements. However, a problem still remains:

PHP Warning: mysqli_stmt::bind_param(): Number of variables doesn't match number of parameters in prepared statement in

Here is the code:

$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;

Thanks!

The error was trivial, question marks in the SQL statement do not need to be surrounded by a quote (though several other answers on StackOverflow do use quotes).

$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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM