CeebLaj Thoj
CeebLaj Thoj

Reputation: 41

Need help on some logic to perform mysql insert query?

I'm developing a shopping cart using php, now I stuck at some point as follow.

There are tables like: customers, products, orders, order_detail

products table:

id | name | quantity

order_detail table:

order_id | product_id | quantity

I completely done for add product to cart and customer can submit the order to database, admin can remove or delete orders from backend and customers can remove orders list or delete orders from frontend if that ordered still not confirm payment.

Example:

"customer1" order 10 products, order ID is #907987899 and "product1" customer1 order quantity = 2, "product2" customer1 order quantity = 5 and so on.....

if the ordered still not confirm then customer still can remove product from the ordered list, and also can delete the entire ordered.

My problem now is: if Customers or Admin cancel or delete the ordered that still not confirm payment then I want to return product quantity from order_detail table list back to products table. by the time when customer submitted the order then product quantity is subtract from product table.

Here is my code that return quantity back to products:

require '../../init.php';
require $ROOT . '/functions/basic.php';
if(isset($_POST['id']))
{
    $id = htmlspecialchars($_POST['id']);

    $delete = dbQuery("DELETE FROM orders WHERE order_id = '$id'");

    if($delete == true)
    {
        //unlink($ROOT . '/upload/products/' . $image);

        $select_product = dbAll("SELECT product_id, quantity FROM order_detail WHERE order_id = '$id'");

        foreach($select_product as $product)
        {
            $quantity = $product['quantity'];
            $product_id = $product['product_id'];

            $return_product_quantity = dbQuery("UPDATE products SET quantity = (quantity + $quantity) WHERE product_id = $product_id");
        }

        if($return_product_quantity == true)
        {
            $delete_order_detail = dbQuery("DELETE FROM order_detail WHERE order_id = '$id'");
            if($delete_order_detail == true)
            {
                echo "OK";
            }
            else
            {
                echo "Can't delete order detail information";
            }
        }


    }
    else
    {
        echo "Can't delete order row";
    }
}

but the query it seem not work as my required, so please help me how to handle this kind of logic to perform my required.

Thanks in advance.

Upvotes: 0

Views: 106

Answers (1)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 520878

You are trying to use the variable quantity in your UPDATE even though it has no value. Try this instead:

$return_product_quantity = dbQuery("UPDATE products
                           SET quantity = ((SELECT quantity FROM products WHERE product_id = $product_id) + $quantity)
                           WHERE product_id = $product_id");

Upvotes: 1

Related Questions