Php mysql更新或插入多条记录(如果表中不存在)

Php mysql更新或插入多条记录(如果表中不存在),php,mysql,Php,Mysql,mysql数据库中有一个名为“inventory\u item”的表。“id”、“产品id”和“数量”是表中的列。“id”是主键,在插入记录时自动生成 当用户提交要向表中插入多条记录的表单时,可以在foreach循环中收集产品ID及其数量的所有数据 因此,我需要同时插入多条记录,并且仅当“product_id”已存在于表中时才应更新数量,而不作为新记录插入 REPLACE INTO table.inventory_item (product_category_id, quantity) SELE

mysql数据库中有一个名为“inventory\u item”的表。“id”、“产品id”和“数量”是表中的列。“id”是主键,在插入记录时自动生成

当用户提交要向表中插入多条记录的表单时,可以在foreach循环中收集产品ID及其数量的所有数据

因此,我需要同时插入多条记录,并且仅当“product_id”已存在于表中时才应更新数量,而不作为新记录插入

REPLACE INTO table.inventory_item (product_category_id, quantity) SELECT '$quantity' ,'$pcid';
这是我的代码块

foreach ($dataArray as $value) { 
    $pcid = $value["pcid"];
    $quantity = $value["quantity"];
    $sql = "
        UPDATE table.inventory_item
        SET quantity='$quantity'
        WHERE product_category_id='$pcid'
        IF ROW_COUNT()=0
        INSERT INTO table.inventory_item
            (product_category_id, quantity)
        VALUES ('$pcid', '$quantity')
    ";
    $result = $conn->query($sql);
    var_dump($result);
}

插入到。。。。。在重复键上…是您的朋友。通过这种组合,您可以插入新记录或更新现有记录。为此,在定义行的字段上必须有一个唯一的键,例如:样本中的产品\类别\ id

*具有唯一键的表**

CREATE TABLE `table` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `product_id` varchar(32) CHARACTER SET latin1 DEFAULT NULL,
  `quantity` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `product_id` (`product_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
样本

mysql> select * from `table`;
Empty set (0,00 sec)

mysql> INSERT into `table` (product_id,quantity) Values ('p1',9),('p2',13) ON DUPLICATE KEY UPDATE quantity=VALUES(quantity);
Query OK, 2 rows affected (0,01 sec)
Records: 2  Duplicates: 0  Warnings: 0

mysql> select * from `table`;
+----+------------+----------+
| id | product_id | quantity |
+----+------------+----------+
|  9 | p1         |        9 |
| 10 | p2         |       13 |
+----+------------+----------+
2 rows in set (0,00 sec)

mysql> INSERT into `table` (product_id,quantity) Values ('p3',9),('p2',15) ON DUPLICATE KEY UPDATE quantity=VALUES(quantity);
Query OK, 3 rows affected (0,00 sec)
Records: 2  Duplicates: 1  Warnings: 0

mysql> select * from `table`;
+----+------------+----------+
| id | product_id | quantity |
+----+------------+----------+
|  9 | p1         |        9 |
| 10 | p2         |       15 |
| 11 | p3         |        9 |
+----+------------+----------+
3 rows in set (0,00 sec)

mysql>

在这里,您可以根据您的要求使用以下任何一种

替换为

如果该记录在表中不可用,它将简单地插入else;如果该记录在表中可用,它将删除该记录并插入新记录

REPLACE INTO table.inventory_item (product_category_id, quantity) SELECT '$quantity' ,'$pcid';
重复密钥更新时

如果记录在表中不可用,则只需插入else即可(如果记录在运行相应的update命令时可用)

INSERT INTO table.inventory_item (product_category_id, quantity) VALUES ('$pcid', '$quantity')" ON DUPLICATE KEY UPDATE table.inventory_item SET quantity='$quantity' WHERE product_category_id='$pcid';

希望这能有所帮助。

您只是想用现有项目的先前数量更新数量,还是用旧数量添加?您需要发出多条语句,因此确保在事务中(
begin
commit
)这样做,以保持数据完整性。