Specifications

Third, we need to work out the total price and number of items in the cart. For this, we use the
calculate_price() and calculate_items() functions, as follows:
$total_price = calculate_price($cart);
$items = calculate_items($cart);
These functions are located in the book_fns.php function library. The code for them is shown
in Listings 25.11 and 25.12, respectively.
LISTING 25.11 calculate_price() Function from book_fns.phpThis Function Calculates
and Returns the Total Price of the Contents of the Shopping Cart
function calculate_price($cart)
{
// sum total price for all items in shopping cart
$price = 0.0;
if(is_array($cart))
{
$conn = db_connect();
foreach($cart as $isbn => $qty)
{
$query = “select price from books where isbn=’$isbn’”;
$result = mysql_query($query);
if ($result)
{
$item_price = mysql_result($result, 0, “price”);
$price +=$item_price*$qty;
}
}
}
return $price;
}
As you can see, the calculate_price() function works by looking up the price of each item
in the cart in the database. This is somewhat slow, so to avoid doing this more often than we
need to, well store the price (and the total number of items, as well) as session variables and
only recalculate when the cart changes.
LISTING 25.12 calculate_items() Function from book_fns.phpThis Function Calculates
and Returns the Total Number of Items in the Shopping Cart
function calculate_items($cart)
{
// sum total items in shopping cart
$items = 0;
Building Practical PHP and MySQL Projects
P
ART V
564
31 7842 CH25 3/6/01 3:39 PM Page 564