Building A Persistent Shopping Cart With PHP and MySQL
If you take a look around any PHP resource site, you'll notice an exorbitant amount of shopping cart scripts. The fact of the matter is that shopping cart scripts aren't hard to develop. In this article Mitchell shows us how to build a simple shopping cart that persists across multiple browser sessions. He uses PHP, MySQL, and JavaScript to implement each part of the shopping cart.
Building A Persistent Shopping Cart With PHP and MySQL - The ShowCart function (Page 5 of 6 )
At this point we need a way to list all of the items in our shopping cart, as well as a total cost for all of those items. ShowCart handles all of this. It also provides a drop down list for each item, so that its quantity can be easily updated.
ShowCart starts off by using an SQL INNER JOIN query to get a list of items from the cart table, and also each items details from the items table:
$result = mysql_query("select * from cart inner join items on cart.itemId = items.itemId where cart.cookieId = '" . GetCartId() . "' order by items.itemName asc");
Once the list of items is retrieved, each item is displayed as part of a table, as a table row:
while($row = mysql_fetch_array($result)) { // Increment the total cost of all items $totalCost += ($row["qty"] * $row["itemPrice"]); ?> <tr> <td width="15%" height="25"> <font face="verdana" size="1" color="black"> <select name="<?php echo $row["itemId"]; ?>" onChange="UpdateQty(this)"> <?php
The <select> tag contains a trigger for the onChange event, which calls a JavaScript function called UpdateQty. UpdateQty is defined at the top of the ShowCart function, and looks like this:
<script language="JavaScript">
function UpdateQty(item) { itemId = item.name; newQty = item.options[item.selectedIndex].text;
Once called, UpdateQty takes the quantity of the selected item as well as the items ID (which is the name of the drop down list) and passes them as query string variables to cart.php. For example, if I updated the quantity of a product whose ID was 5 to 4, then I would be redirected to the following URL:
cart.php?action=update_item&id=5&qty=4
Lastly, ShowCart displays the total cost of all items in the users cart:
After adding all three games to the shopping cart, here’s how cart.php looked in my browser:
When I clicked on the qty field for SSX Tricky and changed it from 2 to 4, the page automatically updated its quantity and the total price, as shown below:
Just before I wrap up this article, I thought that I should mention the persistence of our shopping cart. If you close your browser after you’ve added some items to your cart and then reopen it, you'll see that those items are still in your cart. This results from the way that we’ve used a cookie to track a session ID that persists for up to one month, meaning that the contents of your cart will remain in-tact for the next month.