I have a shopping cart and would like to display a running total of both the number of items in the cart and the total dollar amount in the cart. Of course I need this to be updated when the quantity of an item in the cart is updated and when a new cart is added. Right now it works when a new item is added, however when the quantity is updated it doesn't display at all.
This is the code to display the running price total:
<?php
if(isset($_SESSION['total_price']))
{
echo ("Total Price = $");
echo ($_SESSION['total_price']);
}
?>
These are the codes that are called when an item is added to the cart and when the quantities are updated:
<?php
include('items.php');
if(isset($POST['new']))
{
$new = $POST['new'];
if(!isset($_SESSION['cart']))
{
$_SESSION['cart'] = array();
$_SESSION['items'] = 0;
$_SESSION['total_price'] = "0";
}
if(isset($_SESSION['cart'][$new]))
$_SESSION['cart'][$new]++;
else
$_SESSION['cart'][$new] = 1;
$_SESSION['total_price'] = calculate_price($_SESSION['cart']);
header("Location: cart.php");
}
if($Update)
{
foreach($SESSION['cart'] as $item => $qty)
{
if($$item=="0")
{
unset($SESSION['cart'][$item]);
}
else
{
$SESSION['cart'][$item] = $$item;
}
}
$SESSION['total_price'] = calculate_price($_SESSION['cart']);
header("Location: cart.php");
}
This is the included items file:
<?php
function calculate_price($cart)
{
$price = 0.0;
if(is_array($cart))
{
mysql_select_db($database_connCart, $connCart);
while($element = each($_SESSION['cart']))
{
$itemno = $element['key'];
$query = "SELECT productPrice FROM products WHERE productItemNo='$itemno'";
$result = mysql_query($query);
if ($result)
{
$item_price = mysql_result($result, 0, "productPrice");
$tprice+=$item_price*$element['value'];
}
}
}
return $tprice;
}
?>
Thanks for helping.