【问题标题】:i want to insert and update the quantity of the specific item id我想插入和更新特定项目 ID 的数量
【发布时间】:2013-03-26 19:56:07
【问题描述】:

如果商品id已经存在,数量应该加上传入数量,否则如果id不存在插入id和数量

我的表:

if  
item_id=array(24,25);

quantity=array(10,2);

这将被插入到表中:

else if 

item_id=array(22,23);
quantity=array(2,4);

数量必须添加到现有项目中

auto_id | item_id |数量

 1        22         12   
 2        23         3

这是一个数组类型的项目 ID 和数量。对不起我的英语,谢谢,

foreach($item_id as $row => $id){

        $items_id = $id;
            foreach($quantity as $row => $id2){
            $qty = $id2;
                $values[] = array(
                        array("item_id" => $items_id,
                        "quantity" => $qty));
                $sql = $this->db->query("SELECT ip_id FROM my_table WHERE item_id = '".$items_id."'");      
                if($sql->num_rows() > 0){

                    $this->db->query("UPDATE my_table SET quantity=quantity+'".$qty."' WHERE item_id='".$items_id."'");
                }else{    
                    $this->db->insert_batch('my_table',$values);
                }
            }

【问题讨论】:

  • 如果我理解正确,您使用 2 个 foreach 语句做错了,您在上面的示例中为每个 id 选择了相同的 2 个数量,您应该使用“array_combine”来从第一个键和第二个键中创建一个数组,然后执行一次 foreach,这将为您提供正确的结果。

标签: php javascript jquery mysql codeigniter


【解决方案1】:

跳过所有代码并使用简单的ON DUPLICATE KEY ... 构造:

INSERT INTO yourtable (id, quantity) VALUES ($id, $quantity)
ON DUPLICATE KEY UPDATE quantity=quantity+VALUES(quantity)

【讨论】:

  • 只要确保你的 id 列是一个主键。很可能只是一个提醒。
  • item_id插入重复值,也是数量
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-27
  • 2021-08-25
  • 1970-01-01
  • 2021-10-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多