我想插入和更新特定项目id的数量


i want to insert and update the quantity of the specific item id

如果商品id已经存在,则数量应与到货数量相加;如果id不存在,则插入id和数量

my_table:

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 | quantity

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

跳过所有这些代码,使用一个简单的ON DUPLICATE KEY ...结构:

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