Integrating the Cart with Your Storefront


In this section, you'll make modifications to the showitem.php script from Chapter 22. 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 39 of the original script, so that's where we start in Listing 23.1.

Listing 23.1. New Lines in showitem.php

39:   <p><strong>Price:</strong> \$".$item_price."</p> 40:   <form method=\"post\" action=\"addtocart.php\">"; 41: 42:   //free result 43:   mysqli_free_result($get_item_res); 44: 45:   //get colors 46:   $get_colors_sql = "SELECT item_color FROM store_item_color WHERE 47:                     item_id = '".$_GET["item_id"]."' ORDER BY item_color"; 48:   $get_colors_res = mysqli_query($mysqli, $get_colors_sql) 49:                     or die(mysqli_error($mysqli)); 50: 51:    if (mysqli_num_rows($get_colors_res) > 0) { 52:       $display_block .= "<p><strong>Available Colors:</strong><br/> 53:       <select name=\"sel_item_color\">"; 54: 55:       while ($colors = mysqli_fetch_array($get_colors_res)) { 56:         $item_color = $colors['item_color']; 57:         $display_block .= "<option value=\"".$item_color."\">". 58:         $item_color."</option>"; 59:       } 60:       $display_block .= "</select>"; 61:   } 62: 63:   //free result 64:   mysqli_free_result($get_colors_res); 65: 66:   //get sizes 67:   $get_sizes_sql = "SELECT item_size FROM store_item_size WHERE 68:                    item_id = ".$_GET["item_id"]." ORDER BY item_size"; 69:   $get_sizes_res = mysqli_query($mysqli, $get_sizes_sql) 70:                    or die(mysqli_error($mysqli)); 71: 72:   if (mysqli_num_rows($get_sizes_res) > 0) { 73:       $display_block .= "<p><strong>Available Sizes:</strong><br/> 74:       <select name=\"sel_item_size\">"; 75: 76:       while ($sizes = mysqli_fetch_array($get_sizes_res)) { 77:           $item_size = $sizes['item_size']; 78:           $display_block .= "<option value=\"".$item_size."\">". 79:           $item_size."</option>"; 80:       } 81:   } 82: 83:   $display_block .= "</select>"; 84: 85:   //free result 86:   mysqli_free_result($get_sizes_res); 87: 88:   $display_block .= " 89:   <p><strong>Select Quantity:</strong> 90:   <select name=\"sel_item_qty\">"; 91: 92:   for($i=1; $i<11; $i++) { 93:       $display_block .= "<option value=\"".$i."\">".$i."</option>"; 94:   } 95: 96:   $display_block .= " 97:   </select> 98:   <input type=\"hidden\" name=\"sel_item_id\" 99:   value=\"".$_GET["item_id"]."\"/> 100:  <p><input type=\"submit\" name=\"submit\" value=\"Add to Cart\"/></p> 101:  </form> 102:  </td> 103:  </tr> 104:  </table>"; 105: } 106: //close connection to MySQL 107: mysqli_close($mysqli); 108: ?> 109: <html> 110: <head> 111: <title>My Store</title> 112: </head> 113: <body> 114: <?php echo $display_block; ?> 115: </body> 116: </html>

The first change is at the new line 40, 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 53, where the $display_block string is continued to include the opening tag of a <select> element, named sel_item_color. In lines 5758, the colors are put into <option> elements for the user to choose from, instead of simply printing on the screen. Line 60 closes the <select> element.

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

Lines 8894 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 97 closes this <select> element, and line 98 adds a hidden field for the item_id. Line 100 adds the submit button, and line 101 closes the form. We close the connection to MySQL in line 206, and 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 23-1, reflecting the addition of the form elements.

Figure 23.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 simply writes information to the store_shoppertrack table and redirects the user to the view of the shopping cart. We'll create the addtocart.php script first in Listing 23.2 and then tackle the showcart.php script next.

Listing 23.2. The addtocart.php Script

 1:  <?php 2:  session_start(); 3: 4:  //connect to database 5:  $mysqli = mysqli_connect("localhost", "joeuser", "somepass", "testDB"); 6: 7:  if (isset($_POST["sel_item_id"])) { 8:      //validate item and get title and price 9:      $get_iteminfo_sql = "SELECT item_title FROM store_items WHERE 10:                         id = '".$_POST["sel_item_id"]."'"; 11:    $get_iteminfo_res = mysqli_query($mysqli, $get_iteminfo_sql) 12:                        or die(mysqli_error($mysqli)); 13: 14:   if (mysqli_num_rows($get_iteminfo_res) < 1) { 15:        //invalid id, send away 16:        header("Location: seestore.php"); 17:        exit; 18:    } else { 19:        //get info 20:        while ($item_info = mysqli_fetch_array($get_iteminfo_res)) { 21:            $item_title =  stripslashes($item_info['item_title']); 22:        } 23: 24:        //add info to cart table 25:        $addtocart_sql = "INSERT INTO store_shoppertrack 26:                         (session_id, sel_item_id, sel_item_qty, 27:                         sel_item_size, sel_item_color, date_added) 28:                         VALUES ('".$_COOKIE["PHPSESSID"]."', 29:                       '".$_POST["sel_item_id"]."', 30:                       '".$_POST["sel_item_qty"]."' 31:                       '".$_POST["sel_item_size"]."', 32:                       '".$_POST["sel_item_color"]."', now())"; 33:        $addtocart_res = mysqli_query($mysqli, $addtocart_sql) 34:                         or die(mysqli_error($mysqli)); 35: 36:        //redirect to showcart page 37:        header("Location: showcart.php"); 38:        exit; 39:    } 40: 41: } else { 42:   //send them somewhere else 43:   header("Location: seestore.php"); 44:   exit; 45: } 46: ?>

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. Line 5 makes the database connection, and line 7 begins the validation of the actions.

In line 7, the script verifies that a value is present in $_POST["sel_item_id"], meaning that the user came to this script after submitting the proper form. If there is no value, the script jumps down to line 41 and sends the user away in line 43, 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 912 create and issue a SQL query to gather the title of the selected item. Line 14 checks for a result; if there is no result, the user is again redirected away in line 16 because the item selection was not valid.

If the item selection is valid, the script continues on to line 20 and extracts this value from the resultset. The script now has enough information to add the item selection to the store_shoppertrack table, which it does in lines 2534.

After the query has been issued, the user is redirected to showcart.php, which contains 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 23.3 shows the code for showcart.php.

Listing 23.3. The showcart.php Script

 1:   <?php 2:   session_start(); 3: 4:   //connect to database 5:   $mysqli = mysqli_connect("localhost", "joeuser", "somepass", "testDB"); 6: 7:   $display_block = "<h1>Your Shopping Cart</h1>"; 8: 9:   //check for cart items based on user session id 10:  $get_cart_sql = "SELECT st.id, si.item_title, si.item_price, 11:                   st.sel_item_qty, st.sel_item_size, st.sel_item_color FROM 12:                   store_shoppertrack AS st LEFT JOIN store_items AS si ON 13:                   si.id = st.sel_item_id WHERE session_id = 14:                   '".$_COOKIE["PHPSESSID"]."'"; 15:  $get_cart_res = mysqli_query($mysqli, $get_cart_sql) 16:                  or die(mysqli_error($mysqli)); 17: 18:  if (mysqli_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:  } else { 23:      //get info and build cart display 24:      $display_block .= " 25:      <table celpadding=\"3\" cellspacing=\"2\" border=\"1\" width=\"98%\"> 26:      <tr> 27:      <th>Title</th> 28:      <th>Size</th> 29:      <th>Color</th> 30:      <th>Price</th> 31:      <th>Qty</th> 32:      <th>Total Price</th> 33:      <th>Action</th> 34:      </tr>"; 35: 36:      while ($cart_info = mysqli_fetch_array($get_cart_res)) { 37:          $id = $cart_info['id']; 38:          $item_title = stripslashes($cart_info['item_title']); 39:             $item_price = $cart_info['item_price']; 40:             $item_qty = $cart_info['sel_item_qty']; 41:             $item_color = $cart_info['sel_item_color']; 42:             $item_size = $cart_info['sel_item_size']; 43:          $total_price = sprintf("%.02f", $item_price * $item_qty); 44: 45:             $display_block .= " 46:             <tr> 47:             <td align=\"center\">$item_title <br></td> 48:             <td align=\"center\">$item_size <br></td> 49:             <td align=\"center\">$item_color <br></td> 50:             <td align=\"center\">\$ $item_price <br></td> 51:             <td align=\"center\">$item_qty <br></td> 52:             <td align=\"center\">\$ $total_price</td> 53:             <td align=\"center\"><a href=\"removefromcart.php?\">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: <?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. Line 5 makes the database connection, and line 7 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. Lines 1516 issue the query, and line 18 checks for results.

If there are no results, the user has no items in the store_shoppertrack table. 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 2434, with columns defined for all the information in the cart (and then some). Line 36 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 lines 5354, 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 6168.

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

Figure 23.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 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 23.4 shows the complete script.

Listing 23.4. The removefromcart.php Script

 1: <?php 2: session_start(); 3: 4: //connect to database 5: $mysqli = mysqli_connect("localhost", "joeuser", "somepass", "testDB"); 6: 7: if (isset($_GET["id"])) { 8:     $delete_item_sql = "DELETE FROM store_shoppertrack WHERE 9:                         id = '".$_GET["id"]."'and session_id = 10:                        '".$_COOKIE["PHPSESSID"]."'"; 11:    $delete_item_res = mysqli_query($mysqli, $delete_item_sql) 12:                       or die(mysqli_error($mysqli)); 13: 14:    //redirect to showcart page 15:    header("Location: showcart.php"); 16:    exit; 17: } else { 18:    //send them somewhere else 19:    header("Location: seestore.php"); 21:    exit; 22: } 23: ?>

Line 2 continues the user session because you need to match the user's session ID with the records in the store_shoppertrack table. Line 5 makes the database connection, and line 7 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 810) is issued (lines 1112), and the user is redirected to the showcart.php script (line 15), where the item should no longer show up. Try it and see!




Sams Teach Yourself PHP, MySQL And Apache All in One
Sams Teach Yourself PHP, MySQL and Apache All in One (3rd Edition)
ISBN: 0672328739
EAN: 2147483647
Year: 2004
Pages: 327

Similar book on Amazon

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