I want to update the stock quantities of my products in the DB after a purchase.
My code already works fine, but I want to know if there is a best way to do, with only one SQL statement?
// All the product in the member's cart
if ($stmt = $conn->prepare("SELECT product_id, quantity FROM tbl_cart WHERE member_id = ?")) {
$stmt->bind_param("i", $memberId);
$stmt->execute();
$result = $stmt->get_result();
$stmt->close();
$cartItem = $result->fetch_all(MYSQLI_ASSOC);
// Set the quantity after purchase
foreach ($cartItem as $key => $item) {
$stmt = $conn->prepare("UPDATE tbl_product SET stock = stock-? WHERE id = ?");
$stmt->bind_param("ii", $item['quantity'], $item['product_id']);
$stmt->execute();
$stmt->close();
}
}