I'm having trouble with updating the product quantity in my shopping cart.
I use an array, $productArray
, to store the product_id
, product_name
, quantity
, and product_price
from database. I then check if there is already a product with that Product ID in my $_SESSION
. If yes, then update quantity, if not, merge it into $_SESSION
.
The issue here is that I'm not able to reach the code where it checks where the product_id
is already in the session variable, hence it keeps merging the same product to the shopping cart instead of updating the quantity.
My code is below. Please let me know if there are any additional components I should include with my post. Thanks.
case "add":
if(!empty($_POST["qty"])) {
$productById = $db_handle->runQuery("SELECT * FROM products WHERE product_id= " . $_GET["pid"]);
$productArray = array($productById[0] ["product_id"]=>array('product_name'=>$productById[0]["product_name"], 'product_id'=>$productById[0]["product_id"], 'quantity'=>$_POST["qty"], 'product_price'=>$productById[0]["product_price"]));
if (!empty($_SESSION["cart_item"])) {
if (in_array([$productById[0]["product_id"]],$_SESSION["cart_item"])) {
foreach ($_SESSION["cart_item"] as $k => $v) {
if ($productById[0]["product_id"] == $k)
$_SESSION["cart_item"][$k]["quantity"] = $_POST["qty"];
}
} else {
$_SESSION["cart_item"] = array_merge($_SESSION["cart_item"],$productArray);
}
} else {
$_SESSION["cart_item"] = $productArray;
}
}
The statement in_array([$productById[0]["product_id"]],$_SESSION["cart_item"])
will always return false
in your case.
You should change it to isset($productById[0]["product_id"], $_SESSION["cart_item"])
I guest that you save each product info as an element with the key is the product id inside the $_SESSION["cart_item"]
array.