准备语句WHERE ... IN(...)with array parameter

时间:2012-08-08 18:41:33

标签: php mysqli

就我而言,我正在使用LEFT JOIN从多个表中删除,并且需要提供一组要删除的问题ID。问题ID数组是$questions_to_delete

无法通过mysqli将数组绑定为参数是一种痛苦,我已经看了几个SO问题来达到这个目的:

$params = implode(',', array_fill(0, count($questions_to_delete), '?'));
$types = array_fill(0, count($questions_to_delete), 'i');
$delete_questions = $mysqli->prepare('DELETE    ...
                                          FROM questions
                                          LEFT JOIN ...
                                          WHERE questions.id IN ('.$params.')');

call_user_func_array(array(&$delete_questions, 'bind_param'), array_merge($types, $questions_to_delete));
$delete_questions->execute();
$delete_questions->close();

我得到的错误是

警告:mysqli_stmt :: bind_param()[mysqli-stmt.bind-param]:类型定义字符串中的元素数与绑定变量数不匹配

我注意到一些答案使用&$delete_questions$delete_questions,但我对PHP抱怨的内容感到困惑。

1 个答案:

答案 0 :(得分:1)

我没有正确合并$types$questions_to_delete!在我的原始代码中:

// Produces ['i', 'i', 'i', ...]
$types = array_fill(0, count($questions_to_delete), 'i');

// The argument (array_merge) is then ['i', 'i', ..., 'id1', 'id2', ...]
call_user_func_array(array($delete_questions, 'bind_param'), array_merge($types,$questions_to_delete));

最终对我有用的是:

// Produces 'iii..'
$types = str_repeat('i', $questions_to_delete);

// The argument (array_merge) is then ['iii...', 'id1', 'id2', ...]
call_user_func_array(array($delete_questions, 'bind_param'), array_merge(array($types),$questions_to_delete));

因此参数的类型必须是参数数组开头的String。

我真的不明白call_user_func_array如何将array(mysqli_stmt, 'bind_param')作为callable处理,或者为什么参数必须以这种方式构建,我想知道是否有人可以拿出一个解释!