skip to Main Content

I have some code that can add an item to a cart as well as update its quantity if it gets re-added. It also is able to add other items to the cart, but the problem is that when any item that isn’t the first item in the array gets re-added, it makes another array of that item instead of updating the quantity in the original array.

if(isset($_SESSION['cart']) && is_array($_SESSION['cart'])){
   //update quantity if already in cart
                                
   if(array_key_exists($form_data['listing_id'], $_SESSION['cart'])){
      $_SESSION['cart']['quantity'] += $form_data['quantity'];
      //add listing if not in cart
   }else {
        $new_item = array('listing_id' => $form_data['listing_id'], 
        'name' => $form_data['name'], 'slug' => $form_data['slug'], 
        'image_url' => $form_data['image_main'], 'price' => 
        $form_data['price'], 'quantity' => $form_data['quantity']);
        array_push($_SESSION['cart'], $new_item);
    }
}else {
     //add listing to empty cart
     $_SESSION['cart'] = array('listing_id' => $form_data['listing_id'], 
     'name' => $form_data['name'], 'slug' => $form_data['slug'], 
     'image_url' => $form_data['image_main'], 'price' => 
     $form_data['price'], 'quantity' => $form_data['quantity']);
  }

I have also tried the below code to no avail.

if(array_key_exists($form_data['listing_id'], $_SESSION['cart'])){
   $_SESSION['cart']['quantity'] += $form_data['quantity'];
   //add listing if not in cart
}

2

Answers


  1. Chosen as BEST ANSWER
      //check for listing in db
      $listing = $this -> listingModel -> getListingById($form_data['id']);
      if(!$listing){
         die('No listing');
      }    
      if($listing == $_SESSION['cart']['form_id']){
         //update quantity if already in cart
         $_SESSION['cart']['quantity'] += $form_data['quantity'];
      }else {
         //add listing if not in cart  
         $_SESSION['cart'][$form_data['id']] = ['id' => 
         $form_data['id'], 'name' => $listing -> name, 'slug' => $listing -> 
         slug, 'image_main' => $listing -> image_main, 'price' => $listing -> 
         price, 'quantity' => $form_data['quantity']];
      }
      redirect('cart');
    

  2. Assuming that your session array:

    • may only contain 1 cart element and
    • the cart element may contain multiple products and
    • should be easily searchable and mutatable…

    you should create a lookup array with the following structure:

    $_SESSION['cart'][**item id**] = [
        **item details**,
        ...
    ];
    

    After validating the the user action has legitimately submitted a valid product id and quantity (and whatever other customizable data), apply that payload to the session array.

    I don’t know what listingModel‘s getListingById() does exactly, but it should hopefully return a payload which potentially holds how much stock is left. If the user has ordered too much of something, you will need to signal to them that stock is insufficient for their order.

    Once the user action has been validated and sanitized, it is time to push/add data to the session.

    Note, it makes no sense to honor the name, slug, price, etc from the user because USERS ARE NOT TRUSTWORTHY. These values should only be pulled from your database.

    If item is found in the session array, increase the quantity only.

    Otherwise the action is the same if the array is empty or populated — just push the new data into the array. There is no need to declare a parent array before pushing if you are using square brace syntax.

    $listingId = $form_data['id'];
    $listing = $this->listingModel->getListingById($listingId); // reurn null or a populated row as an object
    
    if (!$listing) {
        exit('Sorry, not sorry hacker');
    }
    
    // a potentially irrelevant condition if supply is no concern:  if insufficient stock ($listing->quantity < $form_data['quantity']), return with notification
    
    if (isset($_SESSION['cart'][$listingId])) {
        //update quantity of existing listing
        $_SESSION['cart'][$listingId]['quantity'] += $form_data['quantity'];
    
    } else {
        // push listing into cart
        $_SESSION['cart'][$listingId] = [
            'id' => $listingId, 
            'name' => $listing->name,
            'slug' => $listing->slug,
            'image_main'  => $listing->image_main,
            'price' => $listing->price,
            'quantity' => (int) $form_data['quantity']
        ];
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search