This question has been asked many times in the forum but none have been answered clearly. I am new to PHP programming and was trying to build a shopping cart using PHP sessions. When the user clicks the delete link in my cart, the quantity is reduced, but when the quantity is less than 1 my program shows errors below:
Notice: Undefined offset: 0 in C:\xampp\htdocs\mycart\functions.php on line 25
Notice: Trying to get property of non-object in C:\xampp\htdocs\mycart\functions.php on line 25
Notice: Use of undefined constant item_delete - assumed 'item_delete' in C:\xampp\htdocs\mycart\cart.php on line 47
Here is the source code of my cart.php file
<?php
require 'init.php';
require 'item.php';
//adding to cart
if (isset($_GET['pid']) && empty($_GET['pid']) === false) {
$query = 'SELECT * FROM products where id=' . $_GET['pid'];
$result = $con->query($query);
$product = mysqli_fetch_object($result);
$item = new item();
$item->id = $product->id;
$item->name = $product->name;
$item->price = $product->price;
$item->quantity = 1;
$index = in_cart($item->id);
$cart = unserialize(serialize($_SESSION['cart']));
if ($index === false) {
$_SESSION['cart'][] = $item;
} else {
$cart[$index]->quantity++;
$_SESSION['cart'] = $cart;
}
header("Location:displaycart.php");
}else if ( isset($_GET['view']) ){
disp_cart();
}
if(isset($_GET['delete']) && !empty($_GET['delete'])){
$cart=unserialize(serialize($_SESSION['cart']));
$item_delete=in_cart($_GET['delete']);
if(empty($cart)){
echo "Cart Already Empty <br></Emptybr><a href='index.php'>Continue Shopping</a>";
}else if(!item_delete){
echo "Item Not Found In Cart <br><a href='index.php'>Continue Shopping</a>";
}else if($cart[$item_delete]->quantity==1){
unset($cart[$item_delete]);
header("Location:index.php");
//echo"Item Deleted <br><a href='index.php'>Continue Shopping</a>";
}else{
$cart[$item_delete]->quantity--;
}
$_SESSION['cart']=$cart;
}
?>