2

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

when the submit button is clicked, which was created to insert multiple records to the table using php all the data of product_category_ids and their quantities can be collected in foreach loop.

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

the code block is here..

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

}
1

1 Answer 1

1
$result = $conn->query($sql);

Will always return a resource so this will always be true, you might want to check for number of rows returned though. If there are no row so insert otherwise update

if(mysqli_num_row($result) == 0) {
    //no rows insert
} else { 
    //row exist do whatever you need
}

Or in object oriented

if($result->num_rows == 0) {
     //row doesn't exist
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.