dornc9470 2014-09-08 19:12
浏览 55
已采纳

将复选框数组值添加到MySQL数据库中的多行中

I'm making a promotion tool for WordPress where I'm sending out a newsletter to several recipients. To keep track, the selected recipients will be added to a MySQL database.

Each row in the SQL has id, newsletter_id, recipient_id and promocode (random generated).

My checkbox array is called recipients[], and I need to insert one row each recipient in the database. Can I somehow make a dynamic SQL query where I insert all in one query, or do I need a loop or something to accomplish this? This is my code so far with a for each.

$checkboxes = isset($_POST['recipients']) ? $_POST['recipients'] : array();
foreach(checkboxes as $recipient) {
    $wpdb->query("INSERT INTO " .$wpdb->prefix ."send(newsletter_id, recipient_id, promocode) VALUES(" .$newsletter_id .", " .$recipient .", " .$promocode .");");
}

Are there any better ways to do this? Any suggestions for a solution would be really helpful.

  • 写回答

1条回答 默认 最新

  • du1108 2014-09-08 20:29
    关注

    First we would prepare the set of values as MarcB mentioned. Then we would execute the SQL Query only once outside the loop. Hence will be the fastest approach and fastest loading time.

    Try this out

    $checkboxes = isset($_POST['recipients']) ? $_POST['recipients'] : array();
    $sql = array(); 
    foreach($checkboxes as $recipient) {
        $sql[] = "(" .$newsletter_id .", " .$recipient .", " .$promocode .")";
    }
    mysql_query("INSERT INTO " .$wpdb->prefix ."send(newsletter_id, recipient_id, promocode) VALUES ".implode(",", $sql).";");
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog