I have some issues that I am trying to figure out that have been commented on in my code below. Essentially I need to know how I can get the code to work to remove an item from the cart if 0 is entered in the quantity field or the trash button is clicked on that line. I have tried a lot of session variables and post variables but I can’t seem to find the one that works just for that item and not all of the products that are in the cart.
- How to remove the item from the cart if the quantity is 0.
- How to remove the item from the cart if the “remove” button is clicked.
<?php
session_start();
$page = 'cart';
//DATABASE CONNECTION INFO
include_once ('includes/database.php');
include_once ('includes/header.php');
if(!isset($_COOKIE['loggedIn']))
{
header("location: login.php");
}
if (isset($_POST['update']))
{
for ($x = 0; $x < sizeof($_SESSION['quant']); $x++)
{
$quant_id = 'quant_'.$x;
if($_POST[$quant_id] > 0)
{
$_SESSION['quant'][$x] = $_POST[$quant_id];
}
elseif($_POST[$quant_id] == 0)
{
//HOW DO I REMOVE THE ITEM FROM THE CART IF QUANTITY IS = 0?
}
else
{
echo "Quantity must be greater than 0 to purchase.";
}
}
}
if(isset($_POST['remove']))
{
//HOW DO I REMOVE THE ITEM FROM THE CART IF THE "REMOVE" BUTTON IS CLICKED?
}
if(isset($_POST['submit_order']))
{
header("location: order.php");
}
if(!isset($_SESSION['product_id']))
{
echo '<h2>The cart is empty!</h2>';
}
if($_POST['clear_cart'])
{
session_unset();
echo '<p>Your cart is empty</p>';
echo '<p><a href="catalog.php" class="button">Continue Shopping</a></p>';
}
$t_open = '<table><tr><th>Name</th><th>Each</th><th>Qty</th><th>Delete</th><th>Total</th></tr>';
$t_middle = '';
$t_close = '</table>';
$total = 0;
?>
<form method ="POST">
<?php
for ($x = 0; $x < sizeof($_SESSION['product_id']); $x++)
{
$t_middle .= '<tr>';
$t_middle .= '<td class="name">' .$_SESSION['name'][$x].'</td>';
$t_middle .= '<td class="each">$' .$_SESSION['price'][$x].'</td>';
$t_middle .= '<td class="qty"><input name="quant_'.$x.'" type="text" value="'.$_SESSION['quant'][$x].'"></input></td>';
//IF REMOVE IMAGE IS CLICKED ITEM IS REMOVED FROM CART
$t_middle .= '<td class="delete"><a href="cart.php" name="remove"><i class="far fa-trash-alt fa-lg"></i></a></td>'; //FIX LINK SO THAT IT REMOVES THE ITEM
$t_middle .= '<td class="total">$' .($_SESSION['price'][$x] * $_SESSION['quant'][$x]).'</td>';
$t_middle .= '</tr>';
$total += ($_SESSION['price'][$x] * $_SESSION['quant'][$x]);
}
$t_middle .= '<tr><td colspan ="4">Grand Total: </td><td>$'.$total.'</td></tr>';
$t = $t_open.$t_middle.$t_close;
echo $t;
?>
<input name="update" class="button" type="submit" value="Update Cart">
<input name="clear_cart" class="button" type="submit" value="Clear Cart">
<input name="submit_order" class="button" type="submit" value="Submit Order">
<?php
if(isset($_POST['submit_order']))
{
header('location:order.php');
}
?>
<a href="catalog.php" class="button">Continue Shopping</a>
</form>
<?php
include_once ('includes/footer.php');
?>