【发布时间】:2016-12-03 12:47:13
【问题描述】:
mysql 数据库中有一个名为“inventory_item”的表。 “id”、“product_category_id”和“quantity”是表的列。 “id”是主键,插入记录时自动生成。
当点击提交按钮时,该按钮被创建用于使用 php 向表中插入多条记录,product_category_ids 的所有数据及其数量都可以在 foreach 循环中收集。
所以我需要同时插入这些多条记录,并且只有在表中已经存在“product_category_id”而不作为新记录插入的情况下才应该更新数量。
代码块在这里..
foreach ($dataArray as $value) {
$pcid = $value["pcid"];
$quantity = $value["quantity"];
$sql = "SELECT * FROM inventory_item WHERE product_category_id='$pcid'";
$result = $conn->query($sql);
$row = mysqli_fetch_assoc($result);
$currentQuantity = $row['quantity'];
$newQuantity = $quantity + $currentQuantity;
if ($result == true) {
$sql2 = "IF EXISTS (SELECT * FROM inventory_item WHERE product_category_id='$pcid') UPDATE inventory_item SET quantity=$newQuantity WHERE product_category_id=’$pcid’ ELSE INSERT INTO inventory_item (product_category_id, quantity) VALUES ('$pcid', '$quantity')";
$result = $conn->query($sql2);
} else {
echo 'error';
}
}
【问题讨论】: