Creating an Online Storefront

Creating an Online Storefront
In this short, hands-on lesson, you will create a generic online storefront. You will learn the methods for creating the relevant database tables, as well as the scripts for displaying the information to the user. The examples used in this chapter represent one of an infinite number of possibilities to complete these tasks and are meant to provide a foundation of knowledge rather than a definitive method for completing this task.

In this chapter, you will learn how to

Create relational tables for an online store

Create the scripts to display store categories

Create the scripts to display individual items

ارایه درگاه پرداخت ePayBank.ir برای فروشگاههای ایرانی و وبلاگها

اگر میخواهید برنامه نویسی سایت را به صورت عملی و کاربردی بیاموزید کافیست به سایت mortezasaheb.ir مراجعه نمایید و بسته آموزش طراحی سایت اختصاصی را خریداری نمایید

برای درج تبلیغات اینترنتی در MyCityAd.ir کافیست بعد از مراجعه به این سایت بر روی ثبت آگهی کلیک نمایید و سپس متن آگهی و مشخصات آگهی را بصورت کامل و دقیق پر کنید.

Planning and Creating the Database Tables
Before you tackle the process of creating database tables for an online store, think about the real-life shopping process. When you walk into a store, items are ordered in some fashion: The hardware and the baby clothes aren’t mixed together, the electronics and the laundry detergent aren’t side by side, and so on. Applying that knowledge to database normalization, already you can see that you will need a table to hold categories and a table to hold items. In this simple store, items will each belong to one category.

Next, think about the items themselves. Depending on the type of store you have, your items may or may not have colors, and may or may not have sizes. But all your items will have a name, a description, and a price. Again, thinking in terms of normalization, you can see that you will have one general items table and two additional tables that relate to the general items table.

Table 22.1 shows sample table and field names to use for your online storefront. In a minute, you’ll create the actual SQL statements, but first you should look at this information and try to see the relationships. Ask yourself which of the fields should be primary or unique keys.

Table 22.1. Storefront Table and Field Names Table Name
Field Names

store_categories
id, cat_title, cat_desc

store_items
id, cat_id, item_title, item_price, item_desc, item_image

store_item_size
item_id, item_size

store_item_color
item_id, item_color

As you can see in the following SQL statements, the store_categories table has two fields besides the id field: cat_title and cat_desc, for title and description. The id field is the primary key, and cat_title is a unique field because there’s no reason you would have two identical categories.

mysql> CREATE TABLE store_categories (
-> id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
-> cat_title VARCHAR (50) UNIQUE,
-> cat_desc TEXT
-> );
Query OK, 0 rows affected (0.03 sec)

Next we tackle the store_items table, which has five fields besides the id fieldnone of which are unique keys. The lengths specified in the field definitions are arbitrary; you should use whatever best fits your store.

The cat_id field relates the item to a particular category in the store_categories table. This field is not unique because you will want more than one item in each category. The item_title, item_price, and item_desc (for description) fields are self-explanatory. The item_image field will hold a filenamein this case, the file is assumed to be local to your serverwhich you will use to build an HTML <img> tag when it’s time to display your item information.

mysql> CREATE TABLE store_items (
-> id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
-> cat_id INT NOT NULL,
-> item_title VARCHAR (75),
-> item_price FLOAT (8,2),
-> item_desc TEXT,
-> item_image VARCHAR (50)
-> );
Query OK, 0 rows affected (0.00 sec)

Both the store_item_size and store_item_color tables contain optional information: If you sell books, they won’t have sizes or colors, but if you sell shirts, they will. For each of these tables, no keys are involved because you can associate as many colors and sizes with a particular item as you want.

mysql> CREATE TABLE store_item_size (
-> item_id INT NOT NULL,
-> item_size VARCHAR (25)
-> );
Query OK, 0 rows affected (0.00 sec)

mysql> CREATE TABLE store_item_color (
-> item_id INT NOT NULL,
-> item_color VARCHAR (25)
-> );
Query OK, 0 rows affected (0.00 sec)

These are all the tables necessary for a basic storefrontthat is, for displaying the items you have for sale. Chapter 23, “Creating a Shopping Cart Mechanism,” integrates the user experience into the mix. For now, just concentrate on your inventory.

In Chapter 20, “Creating an Online Address Book,” you learned how to use PHP forms and scripts to add or delete records in your tables. If you apply the same principles to this set of tables, you can easily create an administrative front end to your storefront. We won’t go through that process in this book, but feel free to do it on your own. At this point, I am confident you know enough about PHP and MySQL to complete the tasks.

For now, you can simply issue MySQL queries, via the MySQL monitor or other interface, to add information to your tables. Following are some examples, if you want to follow along with sample data.

Inserting Records into the store_categories Table
The following queries create three categories in your store_categories table: hats, shirts, and books.

mysql> INSERT INTO store_categories VALUES
-> (’1′, ‘Hats’, ‘Funky hats in all shapes and sizes!’);
Query OK, 1 row affected (0.01 sec)

mysql> INSERT INTO store_categories VALUES (’2′, ‘Shirts’, ‘From t-shirts to
-> sweatshirts to polo shirts and beyond.’);
Query OK, 1 row affected (0.00 sec)

mysql> INSERT INTO store_categories VALUES (’3′, ‘Books’, ‘Paperback, hardback,
-> books for school or play.’);
Query OK, 1 row affected (0.00 sec)

In the next section, we’ll add some items to the categories.

Inserting Records into the store_items Table
The following queries add three item records to each category. Feel free to add many more.

mysql> INSERT INTO store_items VALUES (’1′, ’1′, ‘Baseball Hat’, ’12.00′,
-> ‘Fancy, low-profile baseball hat.’, ‘baseballhat.gif’);
Query OK, 1 row affected (0.00 sec)

mysql> INSERT INTO store_items VALUES (’2′, ’1′, ‘Cowboy Hat’, ’52.00′,
-> ’10 gallon variety’, ‘cowboyhat.gif’);
Query OK, 1 row affected (0.01 sec)

mysql> INSERT INTO store_items VALUES (’3′, ’1′, ‘Top Hat’, ’102.00′,
-> ‘Good for costumes.’, ‘tophat.gif’);
Query OK, 1 row affected (0.00 sec)

mysql> INSERT INTO store_items VALUES (’4′, ’2′, ‘Short-Sleeved T-Shirt’,
-> ’12.00′, ’100% cotton, pre-shrunk.’, ‘sstshirt.gif’);
Query OK, 1 row affected (0.00 sec)

mysql> INSERT INTO store_items VALUES (’5′, ’2′, ‘Long-Sleeved T-Shirt’,
-> ’15.00′, ‘Just like the short-sleeved shirt, with longer sleeves.’,
-> ‘lstshirt.gif’);
Query OK, 1 row affected (0.00 sec)

mysql> INSERT INTO store_items VALUES (’6′, ’2′, ‘Sweatshirt’, ’22.00′,
-> ‘Heavy and warm.’, ‘sweatshirt.gif’);
Query OK, 1 row affected (0.00 sec)

mysql> INSERT INTO store_items VALUES (’7′, ’3′, ‘Jane\’s Self-Help Book’,
-> ’12.00′, ‘Jane gives advice.’, ‘selfhelpbook.gif’);
Query OK, 1 row affected (0.00 sec)

mysql> INSERT INTO store_items VALUES (’8′, ’3′, ‘Generic Academic Book’,
-> ’35.00′, ‘Some required reading for school, will put you to sleep.’,
-> ‘boringbook.gif’);
Query OK, 1 row affected (0.00 sec)

mysql> INSERT INTO store_items VALUES (’9′, ’3′, ‘Chicago Manual of Style’,
-> ’9.99′, ‘Good for copywriters.’, ‘chicagostyle.gif’);
Query OK, 1 row affected (0.00 sec)

Inserting Records into the store_item_size Table
The following queries associate sizes with one of the three items in the shirts category and a generic “one size fits all” size to each of the hats (assume that they’re strange hats). On your own, insert the same set of size associations for the remaining items in the shirts category.

mysql> INSERT INTO store_item_size VALUES (1, ‘One Size Fits All’);
Query OK, 1 row affected (0.00 sec)

mysql> INSERT INTO store_item_size VALUES (2, ‘One Size Fits All’);
Query OK, 1 row affected (0.00 sec)

mysql> INSERT INTO store_item_size VALUES (3, ‘One Size Fits All’);
Query OK, 1 row affected (0.00 sec)

mysql> INSERT INTO store_item_size VALUES (4, ‘S’);
Query OK, 1 row affected (0.00 sec)
mysql> INSERT INTO store_item_size VALUES (4, ‘M’);
Query OK, 1 row affected (0.00 sec)

mysql> INSERT INTO store_item_size VALUES (4, ‘L’);
Query OK, 1 row affected (0.00 sec)

mysql> INSERT INTO store_item_size VALUES (4, ‘XL’);
Query OK, 1 row affected (0.00 sec)

Inserting Records into the store_item_color Table
The following queries associate colors with one of the three items in the shirts category. On your own, insert color records for the remaining shirts and hats.

mysql> INSERT INTO store_item_color VALUES (1, ‘red’);
Query OK, 1 row affected (0.00 sec)

mysql> INSERT INTO store_item_color VALUES (1, ‘black’);
Query OK, 1 row affected (0.00 sec)

mysql> INSERT INTO store_item_color VALUES (1, ‘blue’);
Query OK, 1 row affected (0.00 sec)

Displaying Categories of Items
Believe it or not, the most difficult task in this project is now complete. Compared to thinking up categories and items, creating the scripts used to display the information is easy! The first script you will make is one that lists categories and items. Obviously, you wouldn’t want to list all categories and all items all at once as soon as the user walks in the door, but you do want to give the user the option of immediately picking a category, seeing its items, and then picking another category. In other words, this script serves two purposes: It shows the categories and then shows the items in that category.

Listing 22.1 shows the code for seestore.php.

Listing 22.1. Script to View Categories
1: <?php
2: //connect to database
3: $mysqli = mysqli_connect(“localhost”, “joeuser”, “somepass”, “testDB”);
4:
5: $display_block = “<h1>My Categories</h1>
6: <p>Select a category to see its items.</p>”;
7:
8: //show categories first
9: $get_cats_sql = “SELECT id, cat_title, cat_desc FROM
10: store_categories ORDER BY cat_title”;
11: $get_cats_res = mysqli_query($mysqli, $get_cats_sql)
12: or die(mysqli_error($mysqli));
13:
14: if (mysqli_num_rows($get_cats_res) < 1) {
15: $display_block = “<p><em>Sorry, no categories to browse.</em></p>”;
16: } else {
17: while ($cats = mysqli_fetch_array($get_cats_res)) {
18: $cat_id = $cats['id'];
19: $cat_title = strtoupper(stripslashes($cats['cat_title']));
20: $cat_desc = stripslashes($cats['cat_desc']);
21:
22: $display_block .= “<p><strong><a href=\”".$_SERVER["PHP_SELF"].
23: “?cat_id=”.$cat_id.”\”>”.$cat_title.”</a></strong><br/>”
24: .$cat_desc.”</p>”;
25:
26: if (isset($_GET["cat_id"])) {
27: if ($_GET["cat_id"] == $cat_id) {
28: //get items
29: $get_items_sql = “SELECT id, item_title, item_price FROM
30: store_items WHERE cat_id = ‘”.$cat_id.”‘
31: ORDER BY item_title”;
32: $get_items_res = mysqli_query($mysqli, $get_items_sql)
33: or die(mysqli_error($mysqli));
34:
35: if (mysqli_num_rows($get_items_res) < 1) {
36: $display_block = “<p><em>Sorry, no items in this
37: category.</em></p>”;
38: } else {
39: $display_block .= “<ul>”;
40: while ($items = mysqli_fetch_array($get_items_res)) {
41: $item_id = $items['id'];
42: $item_title = stripslashes($items['item_title']);
42: $item_price = $items['item_price'];
42:
42: $display_block .= “<li><a
42: href=\”showitem.php?item_id=”.
43: $item_id.”\”>”.$item_title.”</a></strong>
44: (\$”.$item_price.”)</li>”;
45: }
46:
47: $display_block .= “</ul>”;
48: }
49: //free results
50: mysqli_free_result($get_items_res);
51: }
52: }
53: }
54: }
55: //free results
56: mysqli_free_result($get_cats_res);
57: //close connection to MySQL
58: mysqli_close($mysqli);
59: ?>
60: <html>
61: <head>
62: <title>My Categories</title>
63: </head>
64: <body>
65: <?php echo $display_block; ?>
66: </body>
67: </html>

Given the length of scripts you saw in Chapter 20, these 67 fully functional lines should be a welcome change. In line 3, the database connection is opened because regardless of which action the script is takingshowing categories or showing items in categoriesthe database is necessary.

In line 5, the $display_block string is started, with some basic page title information added to it. Lines 912 create and issue the query to retrieve the category information. Line 14 checks for categories; if none are in the table, a message is printed to the user, and that’s all this script does. However, if categories are found, the script moves on to line 17, which begins a while loop to extract the information.

In the while loop, lines 1820 retrieve the ID, title, and description of the category. String operations are performed to ensure that no slashes are in the text and that the category title is in uppercase for display purposes. Lines 2224 place the category information, including a self-referential page link, in the $display_block string. If a user clicks the link, she will return to this same script, except with a category ID passed in the query string. The script checks for this value in line 26.

If a $_GET["cat_id"] value has been passed to the script because the user clicked on a category link in hopes of seeing listed items, the script builds and issues another query (lines 2933) to retrieve the items in the category. Lines 3547 check for items and then build an item string as part of $display_block. Part of the information in the string is a link to a script called showitem.php, which you’ll create in the next section.

After reaching that point, the script has nothing left to do, so it prints the HTML and value of $display_block. Figure 22.1 shows the outcome of the script when accessed directly; only the category information shows.

Figure 22.1. Categories in the store.

In Figure 22.2, you see what happens when the user clicks on the HATS link: The script gathers all the items associated with the category and prints them on the screen. The user can still jump to another category on this same page, and it will gather the items for that category.

Figure 22.2. Items within a category in the store.

The last piece of the puzzle for this chapter is the creation of the item display page

Displaying Items
The item display page in this chapter simply shows all the item information. In Chapter 23, “Creating a Shopping Cart Mechanism,” you’ll add a few lines to it to make it function with an “add to cart” button. So for now, just assume this is a paper catalog.

Listing 22.2 shows the code for showitem.php.

Listing 22.2. Script to View Item Information
1: <?php
2: //connect to database
3: $mysqli = mysqli_connect(“localhost”, “joeuser”, “somepass”, “testDB”);
4:
5: $display_block = “<h1>My Store – Item Detail</h1>”;
6:
7: //validate item
8: $get_item_sql = “SELECT c.id as cat_id, c.cat_title, si.item_title,
9: si.item_price, si.item_desc, si.item_image FROM store_items
10: AS si LEFT JOIN store_categories AS c on c.id = si.cat_id
11: WHERE si.id = ‘”.$_GET["item_id"].”‘”;
12: $get_item_res = mysqli_query($mysqli, $get_item_sql)
13: or die(mysqli_error($mysqli));
14:
15: if (mysqli_num_rows($get_item_res) < 1) {
16: //invalid item
17: $display_block .= “<p><em>Invalid item selection.</em></p>”;
18: } else {
19: //valid item, get info
20: while ($item_info = mysqli_fetch_array($get_item_res)) {
21: $cat_id = $item_info['cat_id'];
22: $cat_title = strtoupper(stripslashes($item_info['cat_title']));
23: $item_title = stripslashes($item_info['item_title']);
24: $item_price = $item_info['item_price'];
25: $item_desc = stripslashes($item_info['item_desc']);
26: $item_image = $item_info['item_image'];
27: }
28:
29: //make breadcrumb trail
30: $display_block .= “<p><strong><em>You are viewing:</em><br/>
31: <a href=\”seestore.php?cat_id=”.$cat_id.”\”>”.$cat_title.”</a>
32: &gt; “.$item_title.”</strong></p>
33: <table cellpadding=\”3\” cellspacing=\”3\”>
34: <tr>
35: <td valign=\”middle\” align=\”center\”>
36: <img src=\”".$item_image.”\”/></td>
37: <td valign=\”middle\”><p><strong>Description:</strong><br/>”.
38: $item_desc.”</p>
39: <p><strong>Price:</strong> \$”.$item_price.”</p>”;
40:
41: //free result
42: mysqli_free_result($get_item_res);
43:
44: //get colors
45: $get_colors_sql = “SELECT item_color FROM store_item_color WHERE
46: item_id = ‘”.$_GET["item_id"].”‘ ORDER BY item_color”;
47: $get_colors_res = mysqli_query($mysqli, $get_colors_sql)
48: or die(mysqli_error($mysqli));
49:
50: if (mysqli_num_rows($get_colors_res) > 0) {
51: $display_block .= “<p><strong>Available Colors:</strong><br/>”;
52: while ($colors = mysqli_fetch_array($get_colors_res)) {
53: item_color = $colors['item_color'];
54: $display_block .= $item_color.”<br/>”;
55: }
56: }
57: //free result
58: mysqli_free_result($get_colors_res);
59:
60: //get sizes
61: $get_sizes_sql = “SELECT item_size FROM store_item_size WHERE
62: item_id = “.$_GET["item_id"].” ORDER BY item_size”;
63: $get_sizes_res = mysqli_query($mysqli, $get_sizes_sql)
64: or die(mysqli_error($mysqli));
65:
66: if (mysqli_num_rows($get_sizes_res) > 0) {
67: $display_block .= “<p><strong>Available Sizes:</strong><br/>”;
68: while ($sizes = mysqli_fetch_array($get_sizes_res)) {
69: $item_size = $sizes['item_size'];
70: $display_block .= $item_size.”<br/>”;
71: }
72: }
73: //free result
74: mysqli_free_result($get_sizes_res);
75:
76: $display_block .= ”
77: </td>
78: </tr>
79: </table>”;
80: }
81: ?>
82: <html>
83: <head>
84: <title>My Store</title>
85: </head>
86: <body>
87: <?php echo $display_block; ?>
88: </body>
89: </html>

In line 3, the database connection is made because information in the database forms all the content of this page. In line 5, the $display_block string is started, with some basic page title information.

Lines 813 create and issue the query to retrieve the category and item information. This particular query is a table join. Instead of selecting the item information from one table and then issuing a second query to find the name of the category, this query simply joins the table on the category ID to find the category name.

Line 15 checks for a result; if there is no matching item in the table, a message is printed to the user and that’s all this script does. However, if item information is found, the script moves on and gathers the information in lines 2027.

In lines 3032, you create what’s known as a breadcrumb trail. This is simply a navigational device used to get back to the top-level item in the architecture. Those are fancy words that mean “print a link so that you can get back to the category.” The category ID, retrieved from the master query in this script, is appended to the link in the breadcrumb trail.

In lines 3339, you continue to add to the $display_block, setting up a table for information about the item. You use the values gathered in lines 2126 to create an image link, print the description, and print the price. What’s missing are the colors and sizes, so lines 4456 select and print any colors associated with this item, and lines 6172 gather the sizes associated with the item.

Lines 7680 wrap up the $display_block string and the master if…else statement, and because the script has nothing left to do, it prints the HTML (lines 8289) including the value of $display_block. Figure 22.3 shows the outcome of the script when selecting the baseball hat from the hats category. Of course, your display will differ from mine, but you get the idea.