1

就我而言,我正在从多个表中删除,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_questionsvs $delete_questions,但我对 PHP 抱怨的内容感到困惑。

4

1 回答 1

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')a callable,或者为什么必须以这种方式构造参数,我想看看是否有人能提出解释!

于 2012-08-08T19:20:24.503 回答