准备好的声明在哪里..带有数组参数的 IN (..) 中



就我而言,我正在使用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抱怨的内容感到困惑。

我没有正确合并$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));

因此,参数的类型必须是参数数组开头的字符串。

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

最新更新