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).";");
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加
  • ¥15 用ns3仿真出5G核心网网元
  • ¥15 matlab答疑 关于海上风电的爬坡事件检测
  • ¥88 python部署量化回测异常问题
  • ¥30 酬劳2w元求合作写文章
  • ¥15 在现有系统基础上增加功能
  • ¥15 远程桌面文档内容复制粘贴,格式会变化