Jump to content

SHOPPING CART - Add quantity to an existing item in an $_SESSION array.


justineaguas

Recommended Posts

I save the product id and quantity of an order in $_SESSION['cart'] which is an array. I am successful in adding NEW products in the array. However, when a customer buys an item again that exists in the $_SESSION['cart'] already, only the quantity will be added in the same index. That's my only problem as of now. Here is my code:

 

if(isset($_GET['s_id']) && isset($_GET['p_id'])){
    $s_id=$_GET['s_id'];
    $p_id=$_GET['p_id'];
    $qty = $_POST['qty'];
    
    if(isset($_SESSION['cart'])){
        foreach($_SESSION['cart'] as $cart){ 
            //adds quantity to existing product in array
            if($cart['p_id']==$p_id){
                $temp = $cart['qty'];
                $qty = $temp + $qty;
                $_SESSION['cart'][] = array("qty" => $qty);
            }
            //new product in the array
            else {
                $_SESSION['cart'][] = array("qty" => $qty, "p_id" => $p_id);
            }
        }
    }
    else {
        $_SESSION['cart'][] = array("qty" => $qty, "p_id" => $p_id);
    }
    
    //displays cart information
    foreach($_SESSION['cart'] as $value)
    {
        echo "Product Id:" . $value['p_id'] . '<br />' . "Quantity:" . $value['qty'] . "<br />";
    }

 

$s_id = Supplier ID

$p_id = Product ID

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.