Home > OS >  Trying to figure out how to delete item from cart in PHP
Trying to figure out how to delete item from cart in PHP

Time:12-17

I am trying to make an e-commerce website and I can't quite figure out how to get the cart to function. I am able to add amounts to the cart before purchase but I want it to delete the item from the cart when the quantity is set to 0.

if (isset($_POST['update'])) {
    for ($i = 0; $i < sizeof($_SESSION['quantity']); $i  ) {
        $postID = 'qty' . $i;
        $_SESSION['quantity'][$i] = $_POST[$postID];
        if ($_SESSION['quantity'][$i] == 0) {
            unset($_SESSION['shoppingcart'][$i]);
            unset($_SESSION['quantity'][$i]);
            unset($_SESSION['name'][$i]);
            unset($_SESSION['price'][$i]);
        }
    }
}

Here is the cart variable that creates a table of all the products added

<form method="post">
    <?php
    if (!empty($_SESSION['shoppingcart'])) {
    for ($i = 0; $i < sizeof($_SESSION['shoppingcart']); $i  ) {
        $cart .= '<tr>';
        $cart .= '<td>' . $_SESSION['name'][$i] . '</td>';
        $cart .= '<td><input type="text" id="quantity"name="qty' . $i . '"value="' . $_SESSION['quantity'][$i] . '" onkeyup="checkInput()"></td>';
        $cart .= '<td>$' . $_SESSION['price'][$i] . '</td';
        $cart .= '<td>$' . $_SESSION['quantity'][$i] * $_SESSION['price'][$i] . '</td>';
        $cart .= '</tr>';
        $total  = ($_SESSION['quantity'][$i] * $_SESSION['price'][$i]);
        $totalDiscounted  = ($_SESSION['quantity'][$i] * $_SESSION['price'][$i]) / 100 * 30;
    }
</form>

This works when I delete things going from the last piece in the array, going to the first thing added in the array in that order, but when I try to delete the first element or anything out of order first, it gives me an error. "Warning: Undefined array key 0". What am I doing wrong?

CodePudding user response:

The undefined index come from the use of unset(). The indexes of the array will not be re-ordered after unset() call.

Exemple:

$array = [1, 2, 3];
unset($array[1]);
print_r($array); // indexes : 0 and 2. 

You could:

  • use array_values() to re-index arrays.

    unset($_SESSION['shoppingcart'][$i]);
    $_SESSION['shoppingcart'] = array_values($_SESSION['shoppingcart']);
    
  • or, check the presence of the data in the loop :

    for ($i = 0; $i < sizeof($_SESSION['shoppingcart']); $i  ) {
        if (!isset($_SESSION['name'][$i])) {
            continue;
        }
        $cart .= '<tr>';
        //...
    }
    

Another way is to use a data structure for the order:

 // add
 $_SESSION['shoppingcart'][] = [
    'quantity' => 1,
    'name' => 'item',
    'price' => 1.00,
 ];

 // to update an index
 $_SESSION['shoppingcart'][$index]['quantity'] = 2;

 // to remove an index
 unset($_SESSION['shoppingcart'][$index]);

then, use a foreach() to list

 foreach ($_SESSION['shoppingcart'] => $data) {
     // display item
 }
  • Related