I am trying to work on a homework assignment involving adding items to a cart and updating them and removing items from the cart. So far I have been able to add items but now I'm facing issues with the updating of the quantity and removing of items. Could anyone please assist me? Thank you.
<?php
session_start();
include 'dbconnect.php';
include 'functions.php';
// Create an empty cart if it does not exist
if (!isset($_SESSION['cart'])) {
$_SESSION['cart']=array();
}
// Add an item to the cart
$title = $_GET['title'];
$quantity = $_GET['quantity'];
if ($quantity > 0) {
$_SESSION['cart'][$title]= round($quantity,0);
//create an array of current items in the cart
$items = array();
if(isset($_GET['remove']) && (!empty($_GET['remove'] ||
$_GET['remove'] == 0))){
unset($_SESSION['cart'][$_GET['remove']]);
}
?>
<!DOCTYPE html>
<html>
<head>
<title>BOOK SHOP</title>
<link rel="stylesheet" type="text/css" href= "main.css" />
</head>
<body>
<form>
<input type="button" value="Go back" onclick="history.back()">
</form>
<h1>Your Cart </h1>
<?php
$grand_total = 0;
echo '<table border = "1"> <tr> <th> Book Name </th> <th> Price
</th> <th> Qty</th> <th> Total</th></tr> ';
foreach ($_SESSION['cart']as $title => $quantity) {
// get book data
$result =get_product_data($title);
$items[$title]
['bookname'] =$result[0][2];
$items[$title]
['listPrice'] = $result[0][3];
$items[$title]
['quantity']=$quantity;
$book_total = $result[0][3] * $quantity;
$grand_total +=$book_total;
echo '<tr>';
echo '<td>' . $items[$title]['bookname'] . '</td>';
echo '<td>' . $items[$title]['listPrice'] . '</td> ';
echo "<td><input type='text' class='form-control'
name='value'".$items[$title]['quantity'] ."'></td>";
echo '<td>' . sprintf('$%.2f',$book_total) . '</td>';
echo '<td><a href="?remove=' . $title . '">remove</a></td>';
echo '</tr>';
}
}
echo "<td><input type= 'submit' name='even' value='Update' class='btn
btn-warning'></td>";
echo '<tr> <td> </td> <td> </td> <td>TOTAL</td> <td>' .
sprintf('$%.2f',$grand_total) . '</td> ';
echo '</table>';
?>
</body>
</html>
The expected result should be when I remove an item, it removes the item. When updating the quantity, it will update the price and quantity. Instead I receive errors related to an undefined variable and index:
When I remove an item, I get the following:
Notice: Undefined index: title in C:\xampp\htdocs\book_apps\Book Database Connect\add_to_cart.php on line 12
Notice: Undefined index: quantity in C:\xampp\htdocs\book_apps\Book Database Connect\add_to_cart.php on line 14
Notice: Undefined variable: grand_total in C:\xampp\htdocs\book_apps\Book Database Connect\add_to_cart.php on line 73 TOTAL $0.00