Hi everyone,
I just can't seem to be able to delete, add or modify on my shopping cart!
Everytime I press on the "add to cart" button it adds ok, but then I can't remove or modify.
I'll provide whatever is needed to be able to receive help!
can anyone help please?
==================================================
PHP Code:
<?php
session_start();
mysql_connect('localhost', 'root', '') or die(mysql_error ());
mysql_select_db("phplogin") or die(mysql_error());
?>
<?php
$cart = $_SESSION['cart'];
$action = $_GET['action'];
switch ($action)
{
case'add':
if($cart)
{
$cart .= ','.$_GET['id'];
}
else
{
$cart=$_GET['id'];
}
break;
case'delete':
if($cart)
{
$items = explode(',',$cart);
$newcart = '';
foreach ($items as $item)
{
if($_GET['id'] != '$item')
{
if($newcart != '')
{
$newcart .= ','.$item;
}
else
{
$newcart = $item;
}
}
}
}
break;
case 'update':
if ($cart)
{
$newcart = '';
foreach ($_GET as $key => $value)
{
if (stristr($key,'qty'))
{
$id = str_replace('qty','',$key);
$items = ($newcart != '') ? explode(',',$newcart) : explode(',',$cart);
$newcart = '';
}
echo $items;
foreach ($items as $item)
{
if ($id != $item)
{
if ($newcart != '')
{
$newcart .= ','.$item;
}
else
{
$newcart = $item;
}
}
}
}
}
for ($i=1;$i<=$value;$i++)
{
if ($newcart != '')
{
$newcart .= ','.$id;
}
else
{
$newcart = $id;
}
}
break;
}
//$cart = $newcart;
$_SESSION['cart'] = $cart;
?>
<?php
function displayShoppingCart()
{
$cart = $_SESSION['cart'];
if (!cart)
{
return '<p> You have no items in your shopping cart </p>';
}
else
{
$items = explode(',',$cart);
$s = (count($items) >1)?'s':'';
return "<p>You have <a href='cart.php'>" .count($items).' item'.$s." in your shopping cart</a></p>";
}
}
echo displayShoppingCart();
?>
<?php
function showCart() {
$cart = $_SESSION['cart'];
if ($cart) {
$items = explode(',',$cart);
$contents = array();
foreach ($items as $item) {
$contents[$item] = (isset($contents[$item])) ? $contents[$item] + 1 : 1;
}
$output[] = '<form action="cart.php?action=update" method="get" id="cart">';
$output[] = '<table>';
foreach ($contents as $id=>$qty) {
$sql = 'SELECT * FROM products WHERE Prodid = '."'".$id."'";
$result = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_array($result);
extract($row);
$output[] = '<tr>';
$output[] = '<td><a href="cart.php?action=delete&id='.$id.'" class="r">Remove</a></td>';
/*$output[] = '<td>'.$title.' by '.$author.'</td>';*/
$output[] = '<td>£'.$price.'</td>';
$output[] = '<td><input type="text" name="qty'.$id.'" value="'.$qty.'" size="3" maxlength="3" /></td>';
$output[] = '<td>£'.($price * $qty).'</td>';
$total += $price * $qty;
$output[] = '</tr>';
}
$output[] = '</table>';
$output[] = '<p>Grand total: £'.$total.'</p>';
$output[] = '<div><button type="submit">Update cart</button></div>';
$output[] = '</form>';
} else {
$output[] = '<p>Your shopping cart is empty.</p>';
}
return join('',$output);
}
echo showCart();
?>