Been revising my code for my add to cart function and I am having some difficulties with it not updating the quantity if the product is already present in the cart. It only updates it correctly for the first product added to cart.
My UPDATED add to cart code is:
// -------------------------
// Adding item
// -------------------------
case "add":
if(!empty($_POST["quantity"])) {
$productByCode = $db_handle->runQuery("SELECT * FROM products WHERE product_id='" . $_GET["product_id"] . "'");
$itemArray = array($productByCode[0]["product_id"]=>array('product_name'=>$productByCode[0]["product_name"], 'product_description'=>$productByCode[0]["product_description"],
'product_id'=>$productByCode[0]["product_id"], 'quantity'=>$_POST["quantity"], 'product_price'=>$productByCode[0]["product_price"],'image'=>$productByCode[0]["image"]));
if(!empty($_SESSION["cart_item"])) {
if(in_array($productByCode[0]["product_id"], array_keys($_SESSION["cart_item"]))) {
foreach($_SESSION["cart_item"] as $k => $v) {
if($productByCode[0]["product_id"] == $k) {
if(empty($_SESSION["cart_item"][$k]["quantity"])) {
$_SESSION["cart_item"][$k]["quantity"] = 0;
}
$_SESSION["cart_item"][$k]["quantity"] += $_POST["quantity"];
}
}
} else {
$_SESSION["cart_item"] = array_merge($_SESSION["cart_item"],$itemArray);
}
} else {
$_SESSION["cart_item"] = $itemArray;
}
}
break;
Am I missing something in the code?
Thanks. Stan.
Edit: Updated code doesnt work:
// -------------------------
// Adding item
// -------------------------
case "add":
if(!empty($_POST["quantity"])) {
$productByCode = $db_handle->runQuery("SELECT * FROM products WHERE product_id='" . $_GET["product_id"] . "'");
$itemArray = array($productByCode[0]["product_id"]=>array('product_name'=>$productByCode[0]["product_name"], 'product_description'=>$productByCode[0]["product_description"],
'product_id'=>$productByCode[0]["product_id"], 'quantity'=>$_POST["quantity"], 'product_price'=>$productByCode[0]["product_price"],'image'=>$productByCode[0]["image"]));
if(!empty($_SESSION["cart_item"])) {
if(in_array($productByCode[0]["product_id"], array_keys($_SESSION["cart_item"]))) {
foreach($_SESSION["cart_item"] as $k => $v) {
if($productByCode[0]["product_id"] == $k) {
if(empty($_SESSION["cart_item"][$k]["quantity"])) {
**foreach($_SESSION["cart_item"] as $k =>&$v){
$_SESSION["cart_item"][$k]["quantity"] += $_POST["quantity"];
}**
}
$_SESSION["cart_item"][$k]["quantity"] += $_POST["quantity"];
}
}
} else {
$_SESSION["cart_item"] = array_merge($_SESSION["cart_item"],$itemArray);
}
} else {
$_SESSION["cart_item"] = $itemArray;
}
}
break;