Search code examples
phparraysadditioncart

Qty not updating


I'm trying to set up a basic cart session and add products. I've got everything working apart from adding the same item, it doesn't update the quantity consistently.

I've noticed that if I add only one product in the array and try adding the same one again, it does increment. But as soon as there are 2 or more different products, adding an existing one doesn't update the quantity but adds a whole entry in the array.


Solution

  • the reason is when you merge using array_merge. it will only take the elements, and not the keys.

    if(!empty($_POST["p_quantity"])) {
                    $productById = queryFunc("SELECT * FROM products WHERE product_id='" . $_GET["prid"] . "'");
    
    
                    $productArray = array('productid'=>$productById[0]["product_id"], 'name'=>$productById[0]["product_name"], 'quantity'=>$_POST["p_quantity"], 'price'=>$productById[0]["unit_price"], 'weight'=>$productById[0]["unit_quantity"]);
    
                    if(!empty($_SESSION["shopping_cart"])) {
                        if(in_array($productById[0]["product_id"],array_keys($_SESSION["shopping_cart"]))) {
                            foreach($_SESSION["shopping_cart"] as $keys => $values) {
                                    if($productById[0]["product_id"] == $keys) {
                                        if(empty($_SESSION["shopping_cart"][$keys]["quantity"])) {
                                            $_SESSION["shopping_cart"][$keys]["quantity"] = 0;
                                        }
                                        $_SESSION["shopping_cart"][$keys]["quantity"] = $_SESSION["shopping_cart"][$keys]["quantity"] + $_POST["p_quantity"];
                                    }
                            }
                        } else {
                            $_SESSION["shopping_cart"][$productById[0]["product_id"]] = $productArray;
                        }
                    } else {
                        $_SESSION["shopping_cart"] = array();
                        $_SESSION["shopping_cart"][$productById[0]["product_id"] = $productArray;
                    }
                }