Page 326 - Beginning PHP 5.3
P. 326
Part III: Using PHP in Practice
removeItem() does the opposite of addItem() : after verifying the productId field, it removes the
corresponding product from the user ’ s cart array, then refreshes the browser:
function removeItem() {
global $products;
if ( isset( $_GET[“productId”] ) and $_GET[“productId”] > = 1 and $_
GET[“productId”] < = 3 ) {
$productId = (int) $_GET[“productId”];
if ( isset( $_SESSION[“cart”][$productId] ) ) {
unset( $_SESSION[“cart”][$productId] );
}
}
session_write_close();
header( “Location: shopping_cart.php” );
}
Finally, displayCart() displays the user ’ s cart, as well as the list of available products. After
displaying an XHTML page header, the function loops through each item in the cart, displaying the
product name, price, and a Remove link that allows the user to remove the product from his cart. It
also totals the prices of all the products in the cart as it goes, then displays the total below the cart:
< dl >
< ?php
$totalPrice = 0;
foreach ( $_SESSION[“cart”] as $product ) {
$totalPrice += $product- > getPrice();
? >
< dt > < ?php echo $product- > getName() ? > < /dt >
< dd > $ < ?php echo number_format( $product- > getPrice(), 2 ) ? >
< a href=”shopping_cart.php?action=removeItem & amp;productId= < ?php echo
$product- > getId() ? > ” > Remove < /a > < /dd >
< ?php } ? >
< dt > Cart Total: < /dt >
< dd > < strong > $ < ?php echo number_format( $totalPrice, 2 ) ? > < /strong > < /dd >
< /dl >
The displayCart() function then lists the available products, along with their prices. Each product
has a corresponding Add Item link that the shopper can use to add the product to his cart:
< dl >
< ?php foreach ( $products as $product ) { ? >
< dt > < ?php echo $product- > getName() ? > < /dt >
< dd > $ < ?php echo number_format( $product- > getPrice(), 2 ) ? >
< a href=”shopping_cart.php?action=addItem & amp;productId= < ?php echo
$product- > getId() ? > ” > Add Item < /a > < /dd >
< ?php } ? >
< /dl >
288
9/21/09 9:05:15 AM
c10.indd 288
c10.indd 288 9/21/09 9:05:15 AM