Integrating the Cart with Your Storefront

In this section, you'll make modifications to the showitem.php script from Hour 20, "Creating an Online Storefront." The goal is to transform the item information page into an item information page with a form for selecting colors, sizes, and quantities.

In the original script, insert the following before Line 2:

 session_start(); 

Because the shopping cart elements are attached to the user through a session id, the session must be started. The next changes don't occur until what was line 37 of the original script, so that's where we start Listing 21.1.

Listing 21.1 New Lines in showitem.php
  37:    <P><strong>Price:</strong> \$$item_price</p>  38:    <form method=post action=\"addtocart.php\">";  39:    //get colors  40:    $get_colors = "select item_color from store_item_color where  41:         item_id = $item_id order by item_color";  42:    $get_colors_res = mysql_query($get_colors) or die(mysql_error());  43:  44:    if (mysql_num_rows($get_colors_res) > 0) {  45:  46:        $display_block .= "<P><strong>Available Colors:</strong>  47:        <select name=\"sel_item_color\">";  48:  49:        while ($colors = mysql_fetch_array($get_colors_res)) {  50:            $item_color = $colors['item_color'];  51:            $display_block .=  52:             "<option value=\"$item_color\">$item_color</option>";  53:        }  54:  55:        $display_block .= "</select>";  56:    }  57:  58:    //get sizes  59:    $get_sizes = "select item_size from store_item_size where  60:         item_id = $item_id order by item_size";  61:    $get_sizes_res = mysql_query($get_sizes) or die(mysql_error());  62:  63:    if (mysql_num_rows($get_sizes_res) > 0) {  64:  65:        $display_block .= "<P><strong>Available Sizes:</strong>  66:        <select name=\"sel_item_size\">";  67:  68:        while ($sizes = mysql_fetch_array($get_sizes_res)) {  69:            $item_size = $sizes['item_size'];  70:               $display_block .= "  71:                 <option value=\"$item_size\">$item_size</option>";  72:        }  73:  74:        $display_block .= "</select>";  75:    }  76:   77:    $display_block .= "  78:    <P><strong>Select Quantity:</strong>  79:    <select name=\"sel_item_qty\">";  80:  81:    for($i=1; $i<11; $i++) {  82:        $display_block .= "<option value=\"$i\">$i</option>";  83:    }  84:  85:    $display_block .= "  86:    </select>  87:    <input type=\"hidden\" name=\"sel_item_id\" value=\"$_GET[item_id]\">  88:    <P><input type=\"submit\" name=\"submit\" value=\"Add to Cart\"></p>  89:    </form>  90:     </td>  91:    </tr>  92:    </table>";  93: }  94: ?>  95: <HTML>  96: <HEAD>  97: <TITLE>My Store</TITLE>  98: </HEAD>  99: <BODY> 100: <? print $display_block; ?> 101: </BODY> 102: </HTML> 

The first change is at what was line 37, where the $display_block string is continued to include the beginning <form> element. The action of the form is a script called addtocart.php, which you will create in the next section.

The next change occurs at line 47, where the $display_block string is continued to include the opening tag of a <select> element, named sel_item_color. In lines 51-52, the colors are put into <option> elements for the user to choose from, instead of simply printing on the screen. Line 55 closes the <select> element.

The same types of changes are made for item sizes. Lines 66-67 reflect the continuation of the $display_block string to include the <select> element, named sel_item_size.

Lines 70-71 write the colors in <option> elements, and line 74 closes the <select> element.

Lines 77-83 are additions to the script. These lines create a <select> element, called sel_item_qty, for the user to pick how many items to purchase. Line 86 closes this <select> element, and line 87 adds a hidden field for the item_id. Line 88 adds the submit button and line 89 closes the form. The remaining lines are unchanged from the original script.

When viewing the cowboy hat item using the new version of showitem.php, you would see Figure 21.1, reflecting the addition of the form elements.

Figure 21.1. The new cowboy hat item page.

graphics/21fig01.gif

The next step is to create the addtocart.php script.

Adding Items to Your Cart

The addtocart.php script will simply write information to the store_shoppertrack table, and redirect the user to the view of the shopping cart. We'll create the addtocart.php script first, then tackle the showcart.php script next.

Listing 21.2 The addtocart.php Script
   1: <?php   2: session_start();   3:    4: //connect to database   5: $conn = mysql_connect("localhost", "joeuser", "somepass")   6:    or die(mysql_error());   7: mysql_select_db("testDB",$conn) or die(mysql_error());   8:    9: if ($_POST[sel_item_id] != "") {  10:    //validate item and get title and price  11:    $get_iteminfo = "select item_title from store_items  12:         where id = $_POST[sel_item_id]";  13:    $get_iteminfo_res = mysql_query($get_iteminfo)  14:         or die(mysql_error());  15:   16:    if (mysql_num_rows($get_iteminfo_res) < 1) {  17:        //invalid id, send away  18:        header("Location: seestore.php");  19:        exit;  20:    } else {  21:        //get info  22:        $item_title = mysql_result($get_iteminfo_res,0,'item_title');  24:   25:        //add info to cart table  26:        $addtocart = "insert into store_shoppertrack values  27:         ('', '$PHPSESSID', '$_POST[sel_item_id]', '$_POST[sel_item_qty]',  28:         '$_POST[sel_item_size]', '$_POST[sel_item_color]', now())";  29:   30:        mysql_query($addtocart);  31:   32:        //redirect to showcart page  33:        header("Location: showcart.php");  34:        exit;  35:   36:    }  37: } else {  38:    //send them somewhere else  39:    header("Location: seestore.php");  40:    exit;  41: }  42: ?> 

Line 2 continues the user session, which is important because you will need to capture the user's session id, to write to the store_shoppertrack table. Lines 5-7 make the database connection, and line 9 begins the validation of the actions.

In line 9, the script verifies that a value is present in $_POST[sel_item_id], meaning the user came to this script from a form. If there is no value, the script jumps down to line 37 and sends the user away in line 39, and that's it for the script.

However, if there is a value in $_POST[sel_item_id], the next action is to verify that it is a valid value. Lines 11-14 create and issue an SQL query to gather the title of the selected item. Line 16 checks for a result; if there is no result, the user is again redirected away in line 18.

If the selected item is a valid item, the script continues on to line 22 and extracts the value from the result set. The script now has enough information to add the item selection to the store_shoppertrack table, which it does in lines 26-30.

After the query has been issued, the user is redirected to showcart.php, which will contain all cart items. You'll create this in the next section.

Viewing the Cart

Now that you can add items to a cart, you'll want to see them! Listing 21.3 shows the code for showcart.php.

Listing 21.3 The showcart.php Script
   1: <?php   2: session_start();   3: //connect to database   4: $conn = mysql_connect("localhost", "joeuser", "somepass")   5:     or die(mysql_error());   6: mysql_select_db("testDB",$conn) or die(mysql_error());   7:    8: $display_block = "<h1>Your Shopping Cart</h1>";   9:   10: //check for cart items based on user session id  11: $get_cart = "select st.id, si.item_title, si.item_price, st.sel_item_qty,  12: st.sel_item_size, st.sel_item_color from store_shoppertrack as st  13: left join store_items as si on si.id = st.sel_item_id where  14: session_id = '$PHPSESSID'";  15:   16: $get_cart_res = mysql_query($get_cart) or die(mysql_error());  17:   18: if (mysql_num_rows($get_cart_res) < 1) {  19:    //print message  20:    $display_block .= "<P>You have no items in your cart.  21:     Please <a href=\"seestore.php\">continue to shop</a>!</p>";  22:   23: } else {  24:     //get info and build cart display  25:     $display_block .= "  26:     <table celpadding=3 cellspacing=2 border=1 width=98%>  27:    <tr>  28:    <th>Title</th>  29:    <th>Size</th>  30:    <th>Color</th>  31:    <th>Price</th>  32:    <th>Qty</th>  33:    <th>Total Price</th>  34:    <th>Action</th>  35:    </tr>";  36:   37:    while ($cart = mysql_fetch_array($get_cart_res)) {  38:        $id = $cart['id'];  39:        $item_title = stripslashes($cart['item_title']);  40:        $item_price = $cart['item_price'];  41:        $item_qty = $cart['item_qty'];  42:        $item_color = $cart['sel_item_color'];  43:        $item_size = $cart['sel_item_size'];  44:   45:        $total_price = sprintf("%.02f", $item_price * $item_qty);  46:  47:        $display_block .= "<tr>  48:        <td align=center>$item_title <br></td>  49:        <td align=center>$item_size <br></td>  50:        <td align=center>$item_color <br></td>  51:        <td align=center>\$ $item_price <br></td>  52:        <td align=center>$item_qty <br></td>  53:        <td align=center>\$ $total_price</td>  54:        <td align=center><a href=\"removefromcart.php?id=$id\">remove</a></td>  55:        </tr>";  56:    }  57:  58:    $display_block .= "</table>";  59: }  60: ?>  61: <HTML>  62: <HEAD>  63: <TITLE>My Store</TITLE>  64: </HEAD>  65: <BODY>  66: <? print $display_block; ?>  67: </BODY>  68: </HTML> 

Line 2 continues the user session, which is important because you need to match the user's session id with the records in the store_shoppertrack table. Lines 4-6 make the database connection, and line 8 begins the $display_block string, with a heading for the page.

Lines 10-14 represent a joined query, in which the user's saved items are retrieved. The id, sel_item_qty, sel_item_size, and sel_item_color fields are extracted from store_shoppertrack, and the item_title and item_price fields are retrieved from the store_items table, based on the matching information from store_shoppertrack. In other words, instead of printing 2 for the selected item, Cowboy Hat is shown as the title. Line 16 issues the query, and line 18 checks for results.

If there are no results, the user has no items in the store_shoppertrack table, and a message is written to the $display_block string and the script exits and shows the message.

If there are indeed results, the beginning of an HTML table is created in lines 25-35, with columns defined for all the information in the cart (and then some). Line 37 begins the while loop to extract each item from the store_shoppertrack, and this loop continues until line 56, printing the information in the proper table cell.

In line 54, you see a link created for a removal script, which you will create in the next section. Line 58 closes the table, and the script finishes up and prints HTML to the screen in lines 59-68.

Now, go back to an item page and add the item to your cart. After the items are written to the store_shoppertrack table, you should be redirected to the showcart.php page, and your newly selected items should be displayed. Figure 21.2, shows my cart after adding some items.

Figure 21.2. Items added to cart.

graphics/21fig02.gif

The next step is to create the removefromcart.php script.

Removing Items from Your Cart

The removefromcart.php script is quite short because all it does is issue a query and redirect the user to another script. Inevitably, a user will want to weed items out of his cart, and this script enables him to do just that. Listing 21.4 shows the complete script.

Listing 21.4 The removefromcart.php Script
   1: <?php   2: session_start();   3: //connect to database   4: $conn = mysql_connect("localhost", "joeuser", "somepass")   5:     or die(mysql_error());   6: mysql_select_db("testDB",$conn) or die(mysql_error());   7:    8: if ($_GET[id] != "") {   9:    $delete_item = "delete from store_shoppertrack where  10:     id = $_GET[id] and session_id = '$PHPSESSID'";  11:    mysql_query($delete_item) or die(mysql_error());  12:   13:     //redirect to showcart page  14:    header("Location: showcart.php");  15:    exit;  16:   17: } else {  18:    //send them somewhere else  19:    header("Location: seestore.php");  20:    exit;  21: }  22: ?> 

Line 2 continues the user session because you need to match the user's session id with the records in the store_shoppertrack table. Lines 4-6 make the database connection, and line 8 checks for a value in $_GET[id]. If a value does not exist in $_GET[id], the user is not clicking the link from her cart and, thus, is sent away in line 19.

If a value exists in $_GET[id], an SQL query (lines 9-10) is issued (line 11) and the user is redirected to the showcart.php script (line 14), where the item should no longer show up. Try it and see!



Sams Teach Yourself PHP, MySQL and Apache in 24 Hours
Sams Teach Yourself PHP, MySQL and Apache in 24 Hours
ISBN: 067232489X
EAN: 2147483647
Year: 2005
Pages: 263

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net