Page 323 - Beginning PHP 5.3
P. 323
Chapter 10: Preserving State With Query Strings
function addItem() {
global $products;
if ( isset( $_GET[“productId”] ) and $_GET[“productId”] > = 1 and $_
GET[“productId”] < = 3 ) {
$productId = (int) $_GET[“productId”];
if ( !isset( $_SESSION[“cart”][$productId] ) ) {
$_SESSION[“cart”][$productId] = $products[$productId];
}
}
session_write_close();
header( “Location: shopping_cart.php” );
}
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” );
}
function displayCart() {
global $products;
? >
< !DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd” >
< html xmlns=”http://www.w3.org/1999/xhtml” xml:lang=”en” lang=”en” >
< head >
< title > A shopping cart using sessions < /title >
< link rel=”stylesheet” type=”text/css” href=”common.css” / >
< /head >
< body >
< h1 > Your shopping cart < /h1 >
< 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 ) ? >
285
9/21/09 9:05:14 AM
c10.indd 285 9/21/09 9:05:14 AM
c10.indd 285