Php 如果mysql数据库中的表中不存在多条记录,则更新或插入多条记录
mysql数据库中有一个名为“inventory\u item”的表。“id”、“产品类别id”和“数量”是表中的列。“id”是主键,在插入记录时自动生成 单击submit按钮时,可以在foreach循环中收集product_category_ID及其数量的所有数据。submit按钮是使用php创建的,用于向表中插入多条记录 因此,我需要同时插入这些多条记录,并且仅当表中已经存在“product\u category\u id”时才应更新数量,而不作为新记录插入 代码块在这里Php 如果mysql数据库中的表中不存在多条记录,则更新或插入多条记录,php,mysql,Php,Mysql,mysql数据库中有一个名为“inventory\u item”的表。“id”、“产品类别id”和“数量”是表中的列。“id”是主键,在插入记录时自动生成 单击submit按钮时,可以在foreach循环中收集product_category_ID及其数量的所有数据。submit按钮是使用php创建的,用于向表中插入多条记录 因此,我需要同时插入这些多条记录,并且仅当表中已经存在“product\u category\u id”时才应更新数量,而不作为新记录插入 代码块在这里 foreach (
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';
}
}
将始终返回一个资源,因此这将始终为真,但您可能需要检查返回的行数。如果没有行,则插入,否则更新
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
可能重复的
if($result->num_rows == 0) {
//row doesn't exist