0

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.

Example of add to cart not updating quantity

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;
Stan Howe
  • 116
  • 2
  • 11
  • 1
    Your code is vulnerable to [**SQL injection**](https://en.wikipedia.org/wiki/SQL_injection) attacks. You should use prepared statements with bound parameters, via either the [**mysqli**](https://secure.php.net/manual/en/mysqli.prepare.php) or [**PDO**](https://secure.php.net/manual/en/pdo.prepared-statements.php) drivers. [**This post**](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) has some good examples. – Alex Howansky Nov 30 '17 at 15:48
  • As you've now posted your live URL and information about your database structure, you'll want to take this offline *immediately*. Anybody on the net can now wipe out your database. – Alex Howansky Nov 30 '17 at 15:48
  • Linking to a demo isn't the best approach to getting help here. Please review [SO's how to create a Minimal, Verifiable example](https://stackoverflow.com/help/mcve). Please include your html of the form. – Tony Chiboucas Nov 30 '17 at 15:49

3 Answers3

0

Flame suit on:

I believe when you did this

$_SESSION["cart_item"][$v]["quantity"] = $v++;

PHP actually created a copy of the array you're iterating over

Since you want to write to this array, you should explicitly iterate over by reference using &

foreach($_SESSION["cart_item"] as $k =>&$v)...
Kisaragi
  • 2,198
  • 3
  • 16
  • 28
  • My apologies, that line was changed by me to test the output. I have now updated the original post with the code that works. – Stan Howe Nov 30 '17 at 15:57
  • The basic premise remains, once you attempt to write to the array you must do so by reference and not value – Kisaragi Nov 30 '17 at 15:58
  • Edited main post to show code used with the above, still no luck. I dont understand why it works for the first product but then none after that. – Stan Howe Nov 30 '17 at 16:09
  • Anyone else able to offer any help please? – Stan Howe Dec 04 '17 at 11:31
0

Try this here Im storing data in session $pr_id = product Id

adding item to cart
    if(isset($_SESSION['cart_items']))
        {
            //find index of an array if it exits then do not add else add to cart and then
            if (!array_key_exists($pr_id,$_SESSION['cart_items']))
            {
                $_SESSION['cart_items'][$pr_id]['id'] = $pr_id;
                $_SESSION['cart_items'][$pr_id]['quantity'] = $quantity;
            }
        }
        else
        {
            $_SESSION['cart_items'][$pr_id]['id'] = $pr_id;
            $_SESSION['cart_items'][$pr_id]['quantity'] = $quantity;        
        }
        $arr = array();
        $arr['count'] = count($_SESSION['cart_items']);
        $arr['message'] = 'Item successFully added';
        echo json_encode($arr);

this is working code you can make update entry in db

For updating entry or quantity of product

if (array_key_exists($pr_id,$_SESSION['cart_items']))
    {
        $_SESSION['cart_items'][$pr_id]['quantity']=$quantity;
    }
    $arr['count'] = count($_SESSION['cart_items']);
    $arr['message'] = 'Quantity changed successfully. ';
    $arr['status']  = true;
    echo json_encode($arr);
Nilesh Lathe
  • 152
  • 5
  • Thanks for this, I dont really want to change all of the code. I must be missing something really simple. – Stan Howe Nov 30 '17 at 17:20
0

I made same mistake as you did. This is how i resolved it:

Don't use product_id. product_id is a number. Use something that is combination of numbers and letters like product_name. It worked for me.

$productByCode = $db_handle->runQuery("SELECT * FROM products WHERE product_id='" . $_GET["product_name"] . "'");
atymic
  • 3,093
  • 1
  • 13
  • 26