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

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.