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';
}
}
$result = $conn->query($sql);
将始终返回资源,因此这将始终为true,但是您可能需要检查返回的行数。如果没有行,请插入否则进行更新
if(mysqli_num_row($result) == 0) {
//no rows insert
} else {
//row exist do whatever you need
}
或面向对象
if($result->num_rows == 0) {
//row doesn't exist
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句