duanpie2414 2014-10-04 17:19
浏览 97
已采纳

检查php数组的foreach循环中是否存在mysql行

I have an array of items that I am looping over and checking if the value already exists in the database, if it does I would like to update it, if it does not I would like to create a new entry. The first item in the array is seen and returns true, but anything after the first one returns 0 even if I know for a fact that it is in the database with the correct item_name and ticket_id.

I have tried researching before asking, but am stumped at this point. Thanks for any help in advance.

if($func == 'edit') {

        foreach ($addItem as $key => $value) {
            if (empty($key) || $key=='amount_paid') {
    continue;
  }
            $ticket_items = mysql_query("SELECT * FROM ticket_items WHERE ticket_id = '$ticket_id' AND item_name = '$key'");
            if (mysql_num_rows($ticket_items)) {
                print 'Updated '. $key ."
";
                mysql_query("UPDATE ticket_items set item_name='$key', item_price='$value' WHERE ticket_id='$ticket_id'");
            } else {
                print 'Created '. $key ."
";
            mysql_query("INSERT into ticket_items (ticket_id, item_name, item_price) VALUES ('$ticket_id', '$key', '$value')");     
            }
        }
}
  • 写回答

2条回答 默认 最新

  • du9843 2014-10-04 17:30
    关注

    Notice that, in your UPDATE statement, you are updating every row that has the same $ticket_id, regardless of the item_name. It should be:

    UPDATE ticket_items set item_name='$key', item_price='$value' WHERE ticket_id='$ticket_id' AND item_name='$key';
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 请问各位,如何在Jetson nano主控板的Ubuntu系统中安装PyQt5
  • ¥15 MAC安装佳能LBP2900驱动的网盘提取码
  • ¥400 微信停车小程序谁懂的来
  • ¥15 ATAC测序到底用什么peak文件做Diffbind差异分析
  • ¥15 安装ubantu过程中第一个vfat 文件挂载失败
  • ¥20 GZ::CTF如何兼容一些靶机?
  • ¥15 etcd集群部署问题
  • ¥20 谁可以帮我一下问一下各位
  • ¥15 为何重叠加权后love图的SMD与svyCreateTableOne函数绘制基线表的不一致
  • ¥150 求 《小魔指》街机游戏机整合模拟软件