I am making an e-commerce web app and I am trying to write code to handle if the user clicks the add to basket button on an item that is already in the basket but it doesn't seem to work correctly. If the button is clicked for a second time then the first item quantity is overridden by the second
if ($action === 'add_product') {
$id = isset($_REQUEST['id']) ? (int) $_REQUEST['id'] : null;
$price = isset($_REQUEST['price']) ? (float) $_REQUEST['price'] : null;
$quantity = isset($_REQUEST['quantity']) ? (int) $_REQUEST['quantity'] : null;
$name = isset($_REQUEST['name']) ? trim($_REQUEST['name']) : null;
if ($id && $price && $quantity) {
$_SESSION['cart'][$id] = [
'id' => $id,
'price' => $price,
'quantity' => $quantity,
'name' => $name
];
} // if the action is increment, increse the quantity of the item.
} elseif ($action === 'increment' and array_key_exists('id', $_SESSION['cart'][$_REQUEST['id']])) {
$_SESSION['cart'][$_REQUEST['id']]['quantity'] += 1;
//if the action is decrement, decrease the quantity of item by 1
} elseif(array_key_exists('id',$_SESSION['cart'][$_REQUEST['id']))//here is where it is supposed to handle adding the same item twice {
$_SESSION['cart'][$_REQUEST['id']]['quantity'] += 1;
} elseif ($action === 'decrement' and array_key_exists('id', $_SESSION['cart'][$_REQUEST['id']])) {
$_SESSION['cart'][$_REQUEST['id']]['quantity'] -= 1;
if ($_SESSION['cart'][$_REQUEST['id']]['quantity'] <= 0) {
unset($_SESSION['cart'][$_REQUEST['id']]);
}
} elseif ($action === 'remove' and array_key_exists('id', $_SESSION['cart'][$_REQUEST['id']])) {
unset($_SESSION['cart'][$_REQUEST['id']]);
}
I have commented where it is supposed to be adding to the quantity, but it does not add to the quantity and update it simply overrides the old quality and I don't know why. I have also tried if(in_array($id,$_SESSION['cart'][$_REQUEST['id']))
but that also did not work. I don't quite understand why it won't be working so any help is greatly appreciated.