13.09.2016 Views

PHP and MySQL Web Development 4th Ed-tqw-_darksiderg

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Implementing the Shopping Cart<br />

631<br />

Listing 28.11<br />

Continued<br />

$result = $conn->query($query);<br />

if ($result) {<br />

$item = $result->fetch_object();<br />

$item_price = $item->price;<br />

$price +=$item_price*$qty;<br />

}<br />

}<br />

}<br />

return $price;<br />

}<br />

As you can see, the calculate_price() function works by looking up the price of each<br />

item in the cart in the database.This process is somewhat slow, so to avoid doing this<br />

more often than you need to, you store the price (<strong>and</strong> the total number of items, as well)<br />

as session variables <strong>and</strong> recalculate only when the cart changes.<br />

Listing 28.12 calculate_items() Function from book_fns.php—Function That<br />

Calculates <strong>and</strong> Returns the Total Number of Items in the Shopping Cart<br />

function calculate_items($cart) {<br />

// sum total items in shopping cart<br />

$items = 0;<br />

if(is_array($cart)) {<br />

foreach($cart as $isbn => $qty) {<br />

$items += $qty;<br />

}<br />

}<br />

return $items;<br />

}<br />

The calculate_items() function is simpler; it just goes through the cart <strong>and</strong> adds the<br />

quantities of each item to get the total number of items using the array_sum() function.<br />

If there’s not yet an array (if the cart is empty), it just returns 0 (zero).<br />

Saving the Updated Cart<br />

If the user comes to the show_cart.php script by clicking the Save Changes button, the<br />

process is a little different. In this case, the user has arrived via a form submission. If you<br />

look closely at the code, you will see that the Save Changes button is the submit button<br />

for a form.This form contains the hidden variable save. If this variable is set, you know<br />

that you have come to this script from the Save Changes button.This means that the<br />

user has presumably edited the quantity values in the cart, <strong>and</strong> you need to update them.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!