I am trying to create a query inside of my FOR LOOP that will update my products Quantity column. When a customer checks out they create a row in my orders table, from there a row is created in orderdetails for every item purchased.
I have three tables with the following columns
The error I am receiving is
Fatal error: Uncaught Error: Call to a member function execute() on boolean
$newOrder = $conn->prepare("INSERT INTO orders (UserID, Amount) Values ('{$_SESSION['u_id']}','{$_SESSION['$s']}')");
$newOrder->execute();
$ordersid = $newOrder->insert_id;
//Save order details for new order
$cart = json_decode(json_encode($_SESSION['cart']));
//For loop with query that creates a new row for every item
for($i = 0; $i<count($cart); $i++){
$new_Orderdetail = $conn->prepare("INSERT INTO `orderdetails` (`OrderID`,`ProductID`,`Price`,`Quantity`) VALUES(".$ordersid.",".$cart[$i]->id.",".$cart[$i]->price.",".$cart[$i]->quantity.")");
$new_Orderdetail->execute();
$new_Orderdetailid = $new_Orderdetail->insert_id;
echo "$new_Orderdetailid </br>";
$update = $conn->prepare("Update p SET Quantity = Quantity - ".$cart[$i]->quantity." FROM products p where ID = ".$cart[$i]->id"");
$update->execute();
}
Can someone please help me solve why I am receiving this error?
As far as I see the field Quantity
in table products
is of type VARCHAR()
so you must use ''
to add the value.
EDIT: Since you now want the field to be of type INT
, the ''
are no longer required. I've update the code:
// Corrected code
$update = $conn->prepare("UPDATE products SET Quantity=".$cart[$i]->quantity." WHERE ID=".$cart[$i]->id);
And you had two ""
without a dot at the end of the same statement, and by the way the ""
aren't needed here if $cart[$i]->id
is numeric
:
// Sample from your code
FROM products p where ID = ".$cart[$i]->id"");
// Corrected to
FROM products p where ID=".$cart[$i]->id);
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加