This information is placed in the now-familiar $display_block string, which will continue to be built as the script continues.Lines 59–80 represent the query against the address table..
Trang 1[ Team LiB ]
Viewing Records
If you verified your work in the preceding section by issuing queries through the MySQL monitor or
other interface, you probably became tired of typing SELECT * FROM for every table In this
section, you'll create the two-part script that shows you how to select and view records in your
database
Listing 19.3 shows the select-and-view script called selentry.php
Listing 19.3 Script Called selentry.php for Selecting and Viewing a Record
8: //haven't seen the form, so show it
9: $display_block = "<h1>Select an Entry</h1>";
10:
11: //get parts of records
12: $get_list = "select id, concat_ws(', ', l_name, f_name) as display_name 13: from master_name order by l_name, f_name";
14: $get_list_res = mysql_query($get_list) or die(mysql_error());
23: <form method=\"post\" action=\"$_SERVER[PHP_SELF]\">
24: <P><strong>Select a Record to View:</strong><br>
Trang 237: <input type=\"hidden\" name=\"op\" value=\"view\">
38: <p><input type=\"submit\" name=\"submit\"
39: value=\"View Selected Entry\"></p>
57: $display_block = "<h1>Showing Record for $display_name</h1>";
58: //get all addresses
59: $get_addresses = "select address, city, state, zipcode, type
60: from address where master_id = $_POST[sel_id]";
Trang 382: //get all tel
83: $get_tel = "select tel_number, type from telephone where
102: //get all fax
103: $get_fax = "select fax_number, type from fax where
Trang 4123: $get_email = "select email, type from email where
142: //get personal note
143: $get_notes = "select note from personal_notes where
150: $display_block = "<P><strong>Personal Notes:</strong><br>$note"; 151: }
Trang 5As with the addentry.php script, the selentry.php script will perform one of two tasks at anygiven time: it either shows the selection form, or it performs all the SQL queries related to viewingthe record No matter which of the two tasks will be performed, the database still comes into play.Given that, we connect to it in lines 3–5.
The logic that determines the task begins at line 7, with a test for the value of $_POST[op] If thevalue of $_POST[op] is not "view" , the user is not coming from the form and therefore needs tosee the selection form A string called $display_block is started in line 9, and this string will beadded to throughout this task We hope that it will ultimately hold a selection form
In lines 12–14, we select part of the master_name records to build the selection option in the form.For this step, you need only the name and ID of the person whose record you want to select Line 16tests for results of the query If the query has no results, you can't build a form In this case, thevalue of $display_block would be filled with an error message and the script would end, printingthe resulting HTML to the screen
However, assume you have a few records in the master_name table In this case, you have toextract the information from the query results to be able to build the form This is done in lines
28–33, with form elements written to the $display_block string both above and below it Thescript then breaks out of the if else construct and jumps down to line 110, which outputs theHTML and prints the value of $display_block , in this case the form This outcome is shown inFigure 19.4
Figure 19.4 The record selection form.
Trang 6form If that value does not exist, the user is redirected to the selection form In lines 52–55, a queryobtains the name of the user whose record you want to view This information is placed in the now-familiar $display_block string, which will continue to be built as the script continues.
Lines 59–80 represent the query against the address table If the selected individual has no records
in the address table, nothing is added to the $display_block string However, if there are one ormore entries, they are placed in $display_block as unordered list elements, as shown in lines65–79
The same principle is followed for records in the telephone (lines 83–100), fax (lines 103–120),and email (lines 123–140) tables If there are one or more entries, place the results in
$display_block Otherwise, the script moves on Because there can be only one entry perindividual in the personal_notes table, the script checks for the entry beginning in line 143, andmoves on if it doesn't exist If a note exists, it's written in $display_block in lines 147–151.The final action in this part of the script is to print a link in lines 153–154, in case the user wants toreturn to the selection screen After this point, the script exits from the if else construct andprints the HTML to the screen Figure 19.5 shows a record from the record selection script, with oneentry in each table
Trang 7Figure 19.5 An individual's record.
Try this script yourself You should see data only for individuals who have data associated with them.For example, if you have an entry for a friend, and all you have is an email address for that person,you shouldn't see any text relating to address, telephone, fax, or personal notes
[ Team LiB ]
Trang 8Creating the Record Deletion Mechanism
The record deletion mechanism is virtually identical to the script used to view a record In fact, you
can just take the first 42 lines of Listing 19.3 and paste them into a new file, called delentry.php
, and make the following changes:
In lines 7, 37, and 43, change "view" to "delete"
In lines 24 and 39, change "View" to "Delete"
Starting with a new line 45, the remainder of the code for delentry.php is shown in Listing 19.4
Listing 19.4 Script Called delentry.php for Selecting and Deleting a
Trang 970: $display_block = "<h1>Record(s) Deleted</h1>
71: <P>Would you like to
72: <a href=\"$_SERVER[PHP_SELF]\">delete another</a>?</p>";
information related to the selected individual, from all tables Lines 70–72 place a nice message in
$display_block , and the script exits and prints the HTML to the screen An output of the recorddeletion script is shown in Figure 19.6
Figure 19.6 Deleting a record.
Now go back to the record selection form and note that the individual you deleted is no longer in theselection menu
Trang 11[ Team LiB ]
Adding Subentries to a Record
At this point, you've learned to add, delete, and view records What's missing is adding those
additional entries to the related tables—entries for home versus work telephone number, for
example All you need to do is make a few changes to existing scripts
In the selentry.php script in Listing 19.3 , change lines 153–154 to read
$display_block = "<P align=center>
<a href=\"addentry.php?master_id=$_POST[sel_id]\">add info</a>
<a href=\"$_SERVER[PHP_SELF]\">select another</a></p>";
This change simply adds a link to the addentry.php script and also passes it a variable called
$master_id
Now we need to modify the addentry.php script in Listing 19.2 to account for its dual purposes
Here is a summary of the changes to the original script
Replace the first 10 lines of the original addentry.php script with the following snippet:
<?php
if (($_POST[op] != "add") || ($_GET[master_id] != "")) {
//haven't seen the form, so show it
//get first, last names for display/tests validity
$get_names = "select concat_ws(' ', f_name, l_name) as
display_name from master_name where id = $_GET[master_id]"; $get_names_res = mysql_query($get_names) or die(mysql_error());
if (mysql_num_rows($get_names_res) == 1) {
Trang 12<input type=\"text\" name=\"f_name\" size=30 maxlength=75>
<input type=\"text\" name=\"l_name\" size=30 maxlength=75>";
}
$display_block = "<P><strong>Address:</strong><br>
This snippet simply moves around the form elements, printing the first and last name fields only ifthey contain a new record If they contain an addition to a record, the individual's name is extractedfrom the database for aesthetic purposes as well as for a validity check of the ID
Next, find this line:
<input type=\"hidden\" name=\"op\" value=\"add\">
Beneath it, add the following:
<input type=\"hidden\" name=\"master_id\" value=\"$_GET[master_id]\">
This modification ensures the known value of master_id is passed along to the next task
Identify what were lines 49–67 of the original script, beginning with the comment time to add
to tables and ending with obtaining the value of $master_id These lines should be replacedwith the following:
//time to add to tables, so check for required fields
if ((($_POST[f_name] == "") || ($_POST[l_name] == "")) &&
Trang 13or die(mysql_error());
mysql_select_db("testDB",$conn) or die(mysql_error());
if ($_POST[master_id] == "") {
//add to master_name table
$add_master = "insert into master_name values ('', now(),
now(), '$_POST[f_name]', '$_POST[l_name]')";
These lines modify the check for required fields, allowing the script to continue without values for first
and last names, but only if it has a $_POST[master_id] value Then the script connects to the
database to perform all the additions we want it to, but it skips the addition to the master_name
table if a value for $_POST[master_id] exists
Finally, in the section of the script that handles the insertion into the personal_notes table,
change insert into to replace into to handle an update of the notes field
The new script should look Listing 19.5
Listing 19.5 New addentry.php Script
1: <?php
2: if (($_POST[op] != "add") || ($_GET[master_id] != "")) {
3: //haven't seen the form, so show it
14: //get first, last names for display/tests validity
15: $get_names = "select concat_ws(' ', f_name, l_name) as
16: display_name from master_name where id = $_GET[master_id]"; 17: $get_names_res = mysql_query($get_names) or die(mysql_error()); 18:
19: if (mysql_num_rows($get_names_res) == 1) {
Trang 1430: <input type=\"text\" name=\"f_name\" size=30 maxlength=75>
31: <input type=\"text\" name=\"l_name\" size=30 maxlength=75>";
37: <input type=\"text\" name=\"city\" size=30 maxlength=50>
38: <input type=\"text\" name=\"state\" size=5 maxlength=2>
39: <input type=\"text\" name=\"zipcode\" size=10 maxlength=10>
47: <input type=\"text\" name=\"tel_number\" size=30 maxlength=25>
48: <input type=\"radio\" name=\"tel_type\" value=\"home\" checked> home 49: <input type=\"radio\" name=\"tel_type\" value=\"work\"> work
50: <input type=\"radio\" name=\"tel_type\" value=\"other\"> other
51:
52: <P><strong>Fax Number:</strong><br>
53: <input type=\"text\" name=\"fax_number\" size=30 maxlength=25>
54: <input type=\"radio\" name=\"fax_type\" value=\"home\" checked> home 55: <input type=\"radio\" name=\"fax_type\" value=\"work\"> work
56: <input type=\"radio\" name=\"fax_type\" value=\"other\"> other
57:
58: <P><strong>Email Address:</strong><br>
59: <input type=\"text\" name=\"email\" size=30 maxlength=150>
60: <input type=\"radio\" name=\"email_type\" value=\"home\" checked> home 61: <input type=\"radio\" name=\"email_type\" value=\"work\"> work
62: <input type=\"radio\" name=\"email_type\" value=\"other\"> other
63:
64: <P><strong>Personal Note:</strong><br>
65: <textarea name=\"note\" cols=35 rows=5 wrap=virtual></textarea>
Trang 1566: <input type=\"hidden\" name=\"op\" value=\"add\">
67: <input type=\"hidden\" name=\"master_id\" value=\"$_GET[master_id]\"> 68:
69: <p><input type=\"submit\" name=\"submit\" value=\"Add Entry\"></p> 70: </FORM>";
71:
72: } else if ($_POST[op] == "add") {
73: //time to add to tables, so check for required fields
74: if ((($_POST[f_name] == "") || ($_POST[l_name] == "")) &&
86: //add to master_name table
87: $add_master = "insert into master_name values ('', now(),
88: now(), '$_POST[f_name]', '$_POST[l_name]')";
98: //something relevant, so add to address table
99: $add_address = "insert into address values ('', $master_id,
100: now(), now(), '$_POST[address]', '$_POST[city]',
101: '$_POST[state]', '$_POST[zipcode]', '$_POST[add_type]')"; 102: mysql_query($add_address) or die(mysql_error());
103: }
104:
105: if ($_POST[tel_number]) {
106: //something relevant, so add to telephone table
107: $add_tel = "insert into telephone values ('', $master_id,
108: now(), now(), '$_POST[tel_number]', '$_POST[tel_type]')";
109: mysql_query($add_tel) or die(mysql_error());
110: }
111:
Trang 16115: now(), '$_POST[fax_number]', '$_POST[fax_type]')";
116: mysql_query($add_fax) or die(mysql_error());
117: }
118:
119: if ($_POST[email]) {
120: //something relevant, so add to email table
121: $add_email = "insert into email values ('', $master_id,
122: now(), now(), '$_POST[email]', '$_POST[email_type]')";
123: mysql_query($add_email) or die(mysql_error());
124: }
125:
126: if ($_POST[note]) {
127: //something relevant, so add to notes table
128: $add_note = "replace into personal_notes values ('', $master_id, 129: now(), now(), '$_POST[note]')";
130: mysql_query($add_note) or die(mysql_error());
131: }
132:
133: $display_block = "<h1>Entry Added</h1>
134: <P>Your entry has been added Would you like to
135: <a href=\"addentry.php\">add another</a>?</p>";
You can try out this revised script by selecting a record to view and then following the add info
link You should see a form like Figure 19.7
Figure 19.7 Adding to a record.
Trang 17After submitting this form, you can go back through the selection sequence and view the record toverify that your changes have been made.
[ Team LiB ]
Trang 18In this hands-on hour, you applied your basic PHP and MySQL knowledge to the creation of a
personal address book You learned how to create the database table and scripts for record addition,deletion, and simple viewing You also learned the process for adding multiple records attached to asingle master entry
[ Team LiB ]
Trang 19A1: The $_GET superglobal.
2: How many records in the address, email, telephone, and fax tables can you havefor each individual in your master_name table?
A2: As many as you want—it's relational!
Figure 19.8 An individual's record, with multiple entries in tables.2.
Trang 21[ Team LiB ]
Hour 20 Creating an Online Storefront
In this hour's hands-on lesson, the project is creating a generic online storefront You will learn themethods for creating the relevant database tables, as well as the scripts for displaying the
information to the user The examples used in this hour 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 hour, 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
[ Team LiB ]
Trang 22Planning and Creating the Database Tables
Before you tackle the process of creating database tables for a store, think about how you shop inreal life When you walk into a store, items are ordered in some fashion: The hardware and the babyclothes 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 know that you will need a table
to hold categories and a table to hold items These items will each belong to one category
Next, think about the items themselves Depending on the type of store you have, your items may ormay 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 know that you will have onegeneral items table and two additional tables that relate to the general items table
Table 20.1 shows sample table and field names to use for your online storefront In a minute, you'llcreate the actual SQL statements, but first you should look at this information and try to see therelationships appear Ask yourself which of the fields should be primary or unique keys
Table 20.1 Storefront Table and Field Names
As you can see in the following SQL statements, the store_categories table has two fieldsbesides the id field: cat_title and cat_desc , for title and description The id field is theprimary key, and cat_title is a unique field because there's no reason you would have twoidentical categories
Trang 23mysql> 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)
The store_items table has five fields besides the id field, none of which are unique keys Thelengths 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 Thisfield 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 in this case will hold a filename—in this case, the file is assumed to be local to your
server—which 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,
Query OK, 0 rows affected (0.00 sec)
Both the store_item_size and store_item_color tables contain optional information: Ifyou sell books, they won't have sizes or colors, but if you sell shirts, they will For each of thesetables, no keys are involved because you can associate as many colors and sizes with a particularitem 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)
Trang 24In Hour 19 , "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, you know enough about PHP and MySQL to complete
the tasks
For now, 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, we have them all.');
Query OK, 1 row affected (0.00 sec)
mysql> insert into store_categories values ('3', 'Books', 'Paperback,
hardback, books for school and books for play, you name it, we have it.');
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)
Trang 25mysql> 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 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)
Trang 26mysql> 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 yourown, 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)
[ Team LiB ]
Trang 27[ Team LiB ]
Displaying Categories of Items
Believe it or not, the most difficult task in this project is finished 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 will serve two purposes: It will show the categories and then show the items in that
category
Listing 20.1 shows the code for seestore.php
Listing 20.1 Script to View Categories
7: $display_block = "<h1>My Categories</h1>
8: <P>Select a category to see its items.</p>";
9:
10: //show categories first
11: $get_cats = "select id, cat_title, cat_desc from
12: store_categories order by cat_title";
13: $get_cats_res = mysql_query($get_cats) or die(mysql_error());
27:
Trang 2831: from store_items where cat_id = $cat_id
Given the length of scripts in Hour 19 , these 65 fully functional lines should be a welcome change In
lines 3–5 the database connection is opened, because regardless of which action the script is
taking—showing categories or showing items in categories—the database is necessary
In lines 7–8, the $display_block string is started, with some basic page title information Lines
11–13 create and issue the query to retrieve the category information Line 15 checks for categories;
if none were in the table, a message is printed to the user and that's all this script does However, if
Trang 29categories are found, the script moves on to line 19, which begins a while loop to extract theinformation.
In the while loop, lines 20–22 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 inuppercase for display purposes Lines 24–26 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 thissame script, except with a category ID passed in the query string The script checks for this value inline 28
If a $cat_id value has been passed to the script because the user clicked on a category link inhopes of seeing listed items, the script builds and issues another query (lines 30–33) to retrieve theitems in the category Lines 42–53 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 20.1 shows the outcome of the script when accessed directly; only thecategory information shows
Figure 20.1 Categories in the store.
In Figure 20.2 , you see what happens when the user clicked on the HATS link: the script gatheredall the items associated with the category and printed them on the screen The user can still jump to
Trang 30The last piece of the puzzle for this hour is the creation of the item display page.
[ Team LiB ]
Trang 3234: <tr>
35: <td valign=middle align=center><img src=\"$item_image\"></td>
36: <td valign=middle><P><strong>Description:</strong><br>$item_desc</p> 37: <P><strong>Price:</strong> \$$item_price</p>";
38:
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:
56: $get_sizes = "select item_size from store_item_size where
57: item_id = $item_id order by item_size";
58: $get_sizes_res = mysql_query($get_sizes) or die(mysql_error());
Trang 33Lines 10–14 create and issue the query to retrieve the category and item information This particularquery is a table join Instead of selecting the item information from one table and then issuing asecond query to find the name of the category, this query simply joins the table on the category ID
to find the category name
Line 16 checks for a result; if there is no matching item in the table, a message is printed to the userand that's all this script does However, if item information is found, the script moves on and gathersthe information in lines 21–26
In lines 29–31, you create what's known as a "breadcrumb trail." This is simply a navigational deviceused to get back to the top-level item in the architecture Those are fancy words that mean "print alink so you can get back to the category."
In lines 33–37, you continue to add to the $display_block , setting up a table for informationabout the item You use the values gathered in lines 21–26 to create an image link, print the
description, and print the price What's missing are the colors and sizes, so lines 39–53 select andprint any colors associated with this item, and lines 55–69 gather the sizes associated with the item.Lines 71–74 wrap up the $display_block string, and because the script has nothing left to do, itprints the HTML and value of $display_block Figure 20.3 shows the outcome of the scriptwhen selecting the cowboy hat from the hats category Of course, your display will differ from mine,but you get the idea
Figure 20.3 The cowboy hat item page.
Trang 34[ Team LiB ]
Trang 35[ Team LiB ]
Summary
In this hands-on hour, you applied your basic PHP and MySQL knowledge to the creation of astorefront display You learned how to create the database table and scripts for viewing categories,item lists, and single items
[ Team LiB ]
Trang 362: Why don't the store_item_size and store_item_color tables contain any
primary or unique keys?
A2: Presumably, you will have items with more than one color and more than one size
Therefore, item_id is not a primary or unique key Also, items may have the same
colors or sizes, so the item_color and item_size fields must not be primary or
unique either
[ Team LiB ]