简体   繁体   中英

mysql update or insert multiple records if not already exists in a table

there is a table named "inventory_item" in a mysql database. "id", "product_id" and "quantity" are columns of the table. "id" is the primary key and auto generate when a record is inserted.

when the user submit the form which is to insert multiple records to the table all the data of product_ids and their quantities can be collected in foreach loop.

so i need to insert multiple records at the same time and should only update quantity if "product_id" is already exist in the table without inserting as a new record.

here is my code block..

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

INSERT INTO ..... ON DUPLICATE KEY .... ist your friend. with this combination you can insert new records or update exiting records. for this it is necessary to have a unique key on a field that define your row like: product_category_id in your sample

*a table with unique Key**

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;

Sample

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>

Here you can use any one of the following as per your requirement.

REPLACE INTO

if the record is not already available on table it will simply insert else if it is already available on it will delete the record and insert new record.

REPLACE INTO table.inventory_item (product_category_id, quantity) SELECT '$quantity' ,'$pcid';

ON DUPLICATE KEY UPDATE

if the record is not already available on table it will simply insert else if it is already available on run the respective update command.

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';

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM