cart session to save products by size

181 views Asked by At

I have this code to save product in cart. I need to save product and size - quantity x price. At this momment is storing product name, size, quantity and price, but it display the same row. If I add 'product1' size M quanity 1, and if I add 'product1' size S quanitity 1, in the cart I get 'product1' size S (the last size added) quantity 1 (but in the tquan I get 2 products). So how can I make to have for each size of a product, another row.

$_SESSION['CART']['order_token']    = $form_token;
        $arrCart['id']              = $pID;
        $arrCart['quantity']    = $_SESSION['CART']['PRODUCT'][$pID]['size']['quantity'] + $_POST['quantity'];
        $chkQuan = mysqli_fetch_assoc(mysqli_query($link, "SELECT quantity FROM table WHERE id = '".$pID."'"));

            $total =$_SESSION['CART']['tquan']+$_POST['quantity'];
            $arrCart['pret']                = $_POST['product_price'];
            $arrCart['size']                = $_POST['size'];
            $_SESSION['CART']['tquan']      = $total;
            $_SESSION['CART']['PRODUCT'][$pID] = $arrCart;

And this part is for displaying cart

        if(isset($_SESSION['CART']) && $_SESSION['CART']!='') 
        { 

            $endsumm = '';
            $product_total_price = '';
            foreach($_SESSION['CART']['PRODUCT'] as $pID=>$pArr)
            {
                $prod = mysqli_fetch_assoc(mysqli_query($link, "SELECT * FROM table WHERE id='".$pID."'"));
                $product_total_price = $pArr['quantity']*$pArr['pret'];
                $endsumm += $pArr['quantity']*$pArr['pret'];
1

There are 1 answers

2
milan kyada On

Before inserting product in the cart, you should check that product is already in the cart or not.

  • Here in your case you should check for the productid as well as size is available in the cart or not.
    If any one or both condition is not true then insert that product into the cart.
    Otherwise update your cart.

                $total =$_SESSION['CART']['tquan']+$_POST['quantity'];
       $arrCart['pret']= $_POST['product_price'];
       $arrCart['size']= $_POST['size'];
    $_SESSION['CART']['tquan'] = $total;
    $_SESSION['CART']['PRODUCT'][$pID] = $arrCart

if(!in_array($pID, array_map(function($id){return $id[$pID];}, $_SESSION['CART']))){

          if(!in_array($_POST['size'], array_map(function($size){return $size['size'];}, $_SESSION['CART']))){

//Here insert the product into the cart as you were inserted in the question

     }


}