Search code examples
phpshopping-cart

php shopping cart deleting an item


I am trying to build a shopping cart for a PHP project, however, I have ran into a problem. When I add items to the cart session, I have them displayed in a cart summary.

Item 1
Item 2
Item 3

Whenever I delete an item, the other items below it deletes. For example, if I delete Item 2 then Item 3 deletes, as well. If I delete Item 1, Items 2 and 3 deletes, too.

update-cart.php

<code>

if(isset($_GET["removep"]) && isset($_GET["return_url"]) && isset($_SESSION["products"]))
{

$prod_id    = $_GET["removep"]; 
$return_url     = base64_decode($_GET["return_url"]); 
foreach($_SESSION["products"] as $cart_itm)
{

if($cart_itm["prod_id"]!=$prod_id)
{
$products[] = array('prod_name'=>$cart_itm["prod_name"],'prod_id'=>$cart_itm["prod_id"], 'prod_price'=>$cart_itm["prod_price"], 'prod_percent'=>$cart_itm["prod_percent"], 'prod_qty'=>$cart_itm["prod_qty"]);
}
else
{
    $_SESSION["products"] = $products;
}

}
header('Location:'.$return_url);
}

</code>

widget_summary.php

<code>



if(isset($_SESSION['products']))
 {
 $total = 0;
 echo '<ul>';
 foreach ($_SESSION["products"] as $cart_itm)
 {
 $new_price = discount($cart_itm["prod_price"], $cart_itm["prod_percent"]);
 echo '<table class="cart-items">';
 echo    '<tr>';
 echo        '<td>'.$cart_itm["prod_name"].'</td>';
 echo        '<td><span class="remove-item right"><a href="update-cart.php?    removep='.$cart_itm["prod_id"].'&return_url='.$current_url.'">&times;</a></span></td>';
 echo    '</tr>';
 echo    '<tr>';
 echo        '<td id="qty">Qty: '.$cart_itm["prod_qty"].' &times;    $'.$new_price.' = </td>';
            $sub = $cart_itm["prod_qty"] * $new_price;
echo        '<td class="right subtotal">$'.number_format($sub,2).'</td>';
echo    '</tr>';
echo '</table>';
        $subtotal = ($new_price*$cart_itm["prod_qty"]);
        $total = number_format($total + $subtotal, 2);
}

echo '<table class="tbl-summary-footer">';
echo '<tr>';
echo    '<td> Total </td>';
echo    '<td><span class="price_now right"><strong>$'.$total.'</strong>  </span></td>';
echo '</tr>';
echo '<tr>';
echo    '<td><span class="empty-cart"><a href="update-cart.php?emptycart=1&return_url='.$current_url.'">Clear Cart</a></span></td>';
echo    '<td><span class="right"><a href="shopping-cart.php">Check-out!</a></span></td>';
echo '</tr>';
echo '</table>';
echo '</ul>';
}
else
{
echo 'Cart is empty.';
}

</code>

Solution

  • Declare $products before the foreach loop.
    You will need to set the session key 'products' after the loop.