【问题标题】:update or insert multiple records if not exists in a table in mysql database如果 mysql 数据库中的表中不存在,则更新或插入多条记录
【发布时间】: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';
    }

}

【问题讨论】:

标签: php mysql


【解决方案1】:
$result = $conn->query($sql);

将始终返回一个资源,因此这将始终是正确的,但您可能需要检查返回的行数。如果没有行则插入,否则更新

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多