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
Assuming that your session array:
you should create a lookup array with the following structure:
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
‘sgetListingById()
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.