PHP Sessions shopping cart: update product if it's already id the session

后端 未结 4 1441
北海茫月
北海茫月 2021-01-26 09:22

I have struggled to find a solution to a simple shopping cart with $_SESSION. I kept it very simple and this is my code right now

if ( Input::isPos         


        
4条回答
  •  时光说笑
    2021-01-26 09:54

    $postedQuantity = intval($_POST['quantity']);
    $postedProduct = $_POST['product'];
    $postedSize = $_POST['size'];
    
    $productId = $_POST['product'] . $_POST['size'];// concat the product name/Id and //the size form a new array-key.it will be unique.
    
    if(empty($_SESSION)){
    $_SESSION['cart_items'] = array();
    }
    
    if(empty($_SESSION['cart_items'])) {
        $_SESSION['cart_items'][$productId] = array('name'=> $_POST['product'],
                                                'quantity'=> intval($_POST['quantity']),
                                                'size'=>$_POST['size'],
                                     );
    } elseif(!array_key_exists($productId,$_SESSION['cart_items'])) {
        $_SESSION['cart_items'][$productId] = array('name'=> $_POST['product'],
                                      'quantity'=> intval($_POST['quantity']),
                                      'size'=>$_POST['size'],
                                     );
    }
    else { 
       $_SESSION['cart_items'][$productId]['quantity'] += $postedQuantity;
    }
    

提交回复
热议问题