PHP Cart Item Removal

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.

  1. How to remove the item from the cart if the quantity is 0.
  2. 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');
?>

First a bunch of coding issues -

  1. Use ‘require’ for things your page must have for it to work, and require is not a function, so the ()'s around the filename are unnecessary clutter.
  2. The post method form processing code should all be above the start of the html document.
  3. Don’t use the existence of a cookie to determine if someone is logged in. Anyone can submit a cookie to your site and your code would consider them to be logged in. If you are going to use a cookie for this, rather than a session variable, you would need to generate a unique token in the login code, store it in the cookie, store it in a database table, then when the cookie is found to be set, query the database table to find a matching entry, that hasn’t expired, in order to determine what the current user’s id is and consider them to be logged in.
  4. Every header() redirect needs an exit; statement after it to stop php code execution. In all the cases in your code of a header() redirect, the php code after those points will continued to be executed while the browser is requesting the new URL.
  5. Don’t make a series of name/numbered fields - ‘quant_’.$x;. Use an array for the form field name and you would use the item id as the array indexes.
  6. Since the post method form processing code will be above the start of the html document, any user/validation error messages will need to be stored in an array variable, using the field name as the array index. You would then test if this array variable is empty (no errors) before using the form data. To display the user/validation error messages in the html document, you would test, then loop over the array variable at the appropriate point in the html document.
  7. session_unset();. First of all, session_unset() is obsolete and should not be used when using $_SESSION variables. Also, other things can be stored in the session, so to clear the cart, you would only remove the cart session data, not all the session data.

Lastly, if you simplify the cart definition, all your code to add, update, remove an item, and clear the cart will be greatly simplified. You should use an array variable named $_SESSION[‘cart’], with the array indexes being the item ids and the stored values being the quantity. There should be no other item data in the cart.

To display the cart, you would get the item ids from the cart (see array_keys()) and query to get all the other item data. You would loop over the queried item data, getting the corresponding quantity from the cart for each item id.

To update the cart, you would get the item ids from the cart. loop over them and access the corresponding $_POST quantity array entry, and either set the corresponding cart quantity with the new value, unset() the corresponding cart entry for zero values, or setup a user message for negative quantities.

To remove a specific item from the cart, the remove form needs to submit the item id. You would then just unset() the corresponding cart entry.

To clear the cart, you would just unset() the whole $_SESSION[‘cart’] variable.

Sponsor our Newsletter | Privacy Policy | Terms of Service