Chapter 27 Building a Shopping Cart
4. If you are calling the function with the
parameter set to
(or not set—
it defaults to
),show the boxes with the quantities in them as a form with the
Save Changes button at the end.(When you reuse this function after checking
out,you don’t want the user to be able to change her order.)
Nothing is terribly complicated in this function,but it does quite a lot of work,so you
might find reading it through carefully to be useful.
Adding Items to the Cart
If a user has come to the
page by clicking an Add to Cart button,you
have to do some work before you can show her the contents of her cart. Specifically,you
need to add the appropriate item to the cart,as follows.
First, if the user has not put any items in her cart before,she will not have a cart, so
you need to create one:
$_SESSION[‘cart’] = array();
$_SESSION[‘items’] = 0;
To begin with,the cart is empty.
Second,after you know that a cart is set up, you can add the item to it:
$_SESSION[‘cart’][$new] = 1;
Here, you check whether the item is already in the cart.If it is,you increment the quan-
tity of that item in the cart by one. If not,you add the new item to the cart.
Third,you need to work out the total price and number of items in the cart. For this,
you use the
$_SESSION[‘total_price’] = calculate_price($_SESSION[‘cart’]);
$_SESSION[‘items’] = calculate_items($_SESSION[‘cart’]);
These functions are located in the
function library.The code for them is
shown in Listings 27.11 and 27.12,respectively.
Listing 27.11 calculate_price() Function from book_fns.php— Function That
Calculates and Returns the Total Price of the Contents of the Shopping Cart