douzhi1972 2012-08-08 18:41
浏览 27
已采纳

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

In my case, I'm deleting from multiple tables using LEFT JOIN and need to provide an array of question ids to delete. The array of question ids is $questions_to_delete.

Not being able to bind an array as a parameter through mysqli is kind of a pain, and I've looked through a few SO questions to arrive at this:

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

The error I'm getting is

Warning: mysqli_stmt::bind_param() [mysqli-stmt.bind-param]: Number of elements in type definition string doesn't match number of bind variables

I noticed that some answers used &$delete_questions versus $delete_questions, but I'm stumped as to what PHP is complaining about.

  • 写回答

1条回答 默认 最新

  • drjk87189 2012-08-08 19:20
    关注

    I wasn't merging $types and $questions_to_delete correctly! In my original code:

    // 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));
    

    What eventually worked for me was:

    // 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));
    

    So the types of the parameters need to be a String at the beginning of the parameters array.

    I don't really understand how call_user_func_array handles array(mysqli_stmt, 'bind_param') as a callable, or why the parameters have to be constructed this way, and I'd like to see if anyone can come up with an explanation!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口