JavaScript Editor Javascript source editor     Web programming 

Team LiB
Previous Section Next Section

Integrating the Cart with Your Storefront

In this section, you'll make modifications to the showitem.php script from Chapter 21, "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:


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 38 of the original script, so that's where we start Listing 22.1.

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

The first change is at the new line 39, 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 5152, the colors are put into <option> elements for the user to choose from, instead of simply printing on the screen. Line 54 closes the <select> element.

The same types of changes are made for item sizes. Lines 6364 reflect the continuation of the $display_block string to include the <select> element, named sel_item_size. Lines 6869 write the colors in <option> elements, and line 71 closes the <select> element.

Lines 7379 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 82 closes this <select> element, and line 83 adds a hidden field for the item_id. Line 84 adds the submit button and line 85 closes the form. The remaining lines are unchanged from the original script.

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

Figure 22.1. The new baseball hat item page.

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

Adding Items to Your Cart

The addtocart.php script (see Listing 22.2) 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, and then tackle the showcart.php script next.

Listing 22.2. The addtocart.php Script
 1: <?php
 2: session_start();
 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());
 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());
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');
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())";
30:          mysql_query($addtocart);
32:          //redirect to showcart page
33:          header("Location: showcart.php");
34:          exit;
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 need to capture the user's session ID to write to the store_shoppertrack table. Lines 57 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 after submitting the proper 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 1114 create and issue a 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, because the item selection was not valid.

If the item selection is valid, the script continues on to line 22 and extracts this 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 2630.

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 22.3 shows the code for showcart.php.

Listing 22.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());
 8:  $display_block = "<h1>Your Shopping Cart</h1>";
10:  //check for cart items based on user session id
11:  $get_cart = "select, 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 = st.sel_item_id where
14:  session_id = '$PHPSESSID'";
16:  $get_cart_res = mysql_query($get_cart) or die(mysql_error());
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>";
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>";
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['sel_item_qty'];
42:         $item_color = $cart['sel_item_color'];
43:         $item_size = $cart['sel_item_size'];
45:         $total_price = sprintf("%.02f", $item_price * $item_qty);
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:      }
58:      $display_block .= "</table>";
59:  }
60:  ?>
61:  <HTML>
62:  <HEAD>
63:  <TITLE>My Store</TITLE>
64:  </HEAD>
65:  <BODY>
66:  <?php echo $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 46 make the database connection, and line 8 begins the $display_block string, with a heading for the page.

Lines 1014 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, Baseball 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 2535, 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 an item 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 5968.

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 22.2 shows my cart after adding some items.

Figure 22.2. Items added to cart.

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 22.4 shows the complete script.

Listing 22.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());
 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());
13:    //redirect to showcart page
14:   header("Location: showcart.php");
15:   exit;
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 46 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], a SQL query (lines 910) 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!

    Team LiB
    Previous Section Next Section

    JavaScript Editor Javascript source editor     Web programming