1. Trang chủ
  2. » Công Nghệ Thông Tin

PHP & MySQL Everyday Apps for Dummies phần 5 ppt

45 261 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 45
Dung lượng 0,92 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

[www.mysql.com/products/administrator/index.html], or write yourown application in PHP.The order information is added to the database by the shopping cart tion.. applica-Building the Sho

Trang 1

 Shopping cart: You can use several mechanisms to store the shopping

cart while the customer continues to shop, before the order is ted The customer needs to be able to add and remove items from theshopping cart while putting together the final order The most commontechniques for storing the shopping cart contents are

submit-• Database table: More secure, but more overhead.

• Cookies: The customer might have cookies turned off.

• Session variables: Less secure on a shared server.

• Text file: Easy, but less secure.

Other, less common methods are sometimes used

The application in this chapter stores the shopping cart two differentways The procedural program stores the shopping cart items in theMySQL database The object-oriented program stores the shopping cartitems in a session variable

Application functionality designThe basic function of the shopping cart application is to collect the informa-tion needed to complete a customer’s purchase The application should

 Display the products so that the customer can select products to chase This step is provided by the online catalog application, which I

pur-describe in detail in Chapter 5 However, you need to add some tional features to the catalog to allow online purchasing I cover theadditional features in this chapter

addi- Keep track of the products selected by the customer The customer

should be able to see what he has already selected at any time The tomer should also be able to remove any selections

cus- Collect the information needed to ship the product to the customer.

You need the customer’s name and address Also, you need a phonenumber in case of delivery problems An e-mail address is useful forcommunication The application can also collect any informationrequired to compute shipping charges

 Collect the information needed to charge the customer The

applica-tion collects credit card informaapplica-tion, a billing address, and the exactname associated with the credit card In this chapter, the shipping andbilling information are assumed to be the same I do this to keep theexample simple However, for a real-world Web site, you can’t assumethis

 Provide feedback to the customer The customer needs to see the

infor-mation that she entered at all steps along the way and be able to correctinformation Not everyone has perfect typing skills

Trang 2

Creating the Shopping Cart Database

The shopping cart database stores information about the orders It storesgeneral information about the order, such as the customers’ names andaddresses, and the items selected for each order Another important detail toknow is when the order was submitted This application also requires thatthe order store the product information, which appears in the online catalog.The application in this chapter sells products from The Food Shop catalog,which I describe in Chapter 5

Designing the shopping cart databaseThe sample application in this chapter uses a database named OnlineOrders.The database contains two tables One table stores information general

to the order, such as name and address, order number, and so on Thesecond table stores a row for each item ordered, linked to the first table bythe order number

In addition, because the application needs to display the products, it needsaccess to the catalog database

Designing the Customer_Order table

The table named Customer_Ordercontains information related to the order

as a whole, as shown in Table 6-1

You can’t name tables with MySQL-reserved words This table seems like itought to be named Order, but that’s a MySQL-reserved word If you nameyour table Order, it generates a MySQL syntax error and you can spendhours staring at the query, convinced that there’s nothing wrong You can see a list of reserved words at http://dev.mysql.com/doc/mysql/en/reserved-words.html

Table 6-1 Database Table: Customer_Order

Variable Name Type Description

order_number INT(6) Integer assigned by

AUTO_INCREMENT(primary key)

order_date DATE Date when order was added to

table

shipping_fee DECIMAL(9,2) Total shipping cost for the order

sales_tax DECIMAL(9,2) Total sales tax for the order

Trang 3

Variable Name Type Description

submitted ENUM(‘yes’, Order status

’no’)ship_name VARCHAR(50) Ship to: name

ship_street VARCHAR(50) Street address

ship_city VARCHAR(50) City where the order is to be

shipped

ship_state CHAR(2) Two-letter state code

ship_zip CHAR(10) Zip code (Five numbers or zip+4)

email CHAR(50) Customer’s e-mail address

In this design, the order number is an integer assigned sequentially byMySQL Some designs might use an order number with meaningful numbersand/or letters, such as dates or department codes

The shipping fee and sales tax are stored in the order Although they can becomputed, the rates might change in the future Therefore, when looking up

an order, you want to know what the charges were at the time of the order

Designing the Order_Item table

The table named Order_Itemcontains information on each item in the order,

as shown in Table 6-2

Table 6-2 Database Table: Order_Item

table (primary key 1)

item (primary key 2)

catalog_number INT(8) Number assigned to the

product in the catalog

Trang 4

The Order_Itemtable has five fields The first two fields together are the primary key The price is stored so the actual price paid for this item can

be recovered in the future, even if the price has changed

Designing the Food table

The application uses the Foodtable from the online catalog that I design andexplain in Chapter 5 (Specifically, check out Table 5-1.) The application couldaccess the table from that database However, I have added the Foodtable tothe OnlineOrdersdatabase (which I design and explain in this chapter) tosimplify the design

Building the shopping cart databaseYou can create the MySQL database using any of the methods that I discuss

in Chapter 1 The following SQL statement creates this database:

CREATE DATABASE OnlineOrders;

The following SQL statements create the tables:

CREATE TABLE Customer_Order ( order_number INT(6) NOT NULL AUTO_INCREMENT, order_date DATE NOT NULL,

shipping_fee DECIMAL(9,2), sales_tax DECIMAL(9,2), submitted ENUM(“yes”,’no’), ship_name VARCHAR(50), ship_street VARCHAR(50), ship_city VARCHAR(50), ship_state VARCHAR(2), ship_zip VARCHAR(10), email VARCHAR(50), phone VARCHAR(20), PRIMARY KEY(order_number) );

All fields in the preceding code are required to complete the order ing However, only the first two fields are declared NOT NULL When the appli-cation first inserts the order into the database, values are inserted into onlythe first two fields The remaining fields are blank at that time; the values forthose fields are added later Consequently, the remaining fields must beallowed to be blank The PHP application script must ensure that the fieldscontain the appropriate information

process-CREATE TABLE Order_Item ( order_number INT(6) NOT NULL, item_number INT(5) NOT NULL, catalog_number INT(6) NOT NULL, quantity DECIMAL(7,2) NOT NULL, price DECIMAL(9,2) NOT NULL, PRIMARY KEY(order_number,item_number) );

Trang 5

CREATE TABLE Food ( catalog_number INT(6) NOT NULL AUTO_INCREMENT, name VARCHAR(20) NOT NULL,

added_date DATE NOT NULL, category VARCHAR(20) NOT NULL, type VARCHAR(20) NOT NULL, description VARCHAR(255) NOT NULL, price DECIMAL(7,2) NOT NULL, pix VARCHAR(20) NOT NULL DEFAULT

“Missing.jpg”, PRIMARY KEY(catalog_number) );

Accessing the shopping cart databasePHP provides MySQL functions for accessing your database from your PHPscript The MySQL functions are passed the information needed to access thedatabase, such as a MySQL account name and password This account nameand password is not related to any other account name or password that youhave, such as a password to log onto the system

PHP provides two different sets of MySQL functions: mysql functions andmysqli functions The mysqli functions are provided for access to featuresadded in MySQL version 4.1 You can use the mysql functions with version4.1, but you don’t have access to the newer features The mysql or mysqliextension is activated when PHP is installed You must use PHP 5 to use themysqli functions

Because MySQL 4.1 is now the recommended version on the MySQL Web site,

I use the MySQL Improved (mysqli) functions in this chapter I use the dural functions when building the procedural programs I use the object-oriented classes when building the object-oriented programs

proce-If you’re using PHP 4 or for other reasons want to use the mysql functions,rather than the mysqli functions, you might need to make small changes to thesyntax The mysqli functions are very similar to the mysql functions, but somedifferences exist The PHP and MySQL versions are explained in Chapter 1 Thesyntax differences are shown in Appendix C More information about the func-tions is available in the PHP manual at www.php.net/manual/en/ref.mysqli

phpand www.php.net/manual/en/ref.mysql.php

Adding data to the shopping cart databaseThe Foodtable contains the product information You add this data to thedatabase yourself, outside this application To add items to the Food catalog,you can use the mysql client installed with MySQL, any MySQL administra-tion application (such as phpmyadmin [www.phpmyadmin.net] or MySQLAdministrator, which you can download from MySQL

Trang 6

[www.mysql.com/products/administrator/index.html]), or write yourown application in PHP.

The order information is added to the database by the shopping cart tion When customers submit orders, the order and item information isadded to the appropriate table

applica-Building the Shopping Cart Web Pages

The shopping cart application provides the customer with product tion, displayed from an online catalog, similar to the online catalog applica-tion discussed in Chapter 5 The customer selects items from the catalog andputs them into a shopping cart When the customer is satisfied with the con-tents of the shopping cart and submits the order, the application builds theorder, collecting the shipping information and storing the chosen items

informa-Designing the shopping cart Web pagesThe shopping cart application displays five Web pages, in the following order:

1 Product information: The application displays the product information

from an online catalog, as I describe in Chapter 5 The catalog actuallydisplays two different types of pages: the categories page and the prod-uct information page The categories page is the same page designed inChapter 5 The product page is similar, but has some added elementsthat are necessary for online purchasing

2 Shopping cart: The shopping cart Web page displays the items that are

currently in the shopping cart

3 Shipping form: When the customer submits the order, the application

dis-plays a form to collect the shipping address and credit card information

4 Summary page: The summary page displays all the order information,

including the address

5 Confirmation page: When the credit information is approved, the

appli-cation displays a confirmation page, accepting the order and providingany information the customer needs Alternatively, if the customer can-cels the order, a cancellation page is displayed

Designing the product information Web page

In Chapter 5, I describe the online catalog application that displays itemsfrom a catalog The application in the current chapter also displays itemsfrom a catalog Two types of pages are displayed One page is the productcategories page (refer to Figure 5-2) This page is the same for the shoppingcart application as for the online catalog application

Trang 7

The second type of page displays information for products in the selectedcategory The product page for the shopping cart application is similar to theproduct page described in the previous chapter (refer to Figure 5-2), but hassome added components, as shown in Figure 6-1.

Notice the following additions on this page:

 View Shopping Cart button: A new submit button — View Shopping

Cart — is added to the upper-right corner of the page that allows tomers to view the current contents of their shopping carts This button

cus-is also added to the categories page

 The lbs column: This column allows customers to enter the quantity

they want for each item The food catalog allows users to specify thenumber of pounds desired The items display with 0 (zero) pounds Thecustomer can change the amount

 Add Items to Shopping Cart button: A new submit button — Add Items

to Shopping Cart — is added

The new elements on the page are added so the customer can select ucts to purchase

prod-Figure 6-1:

The productpagedisplayed bythe onlineordersapplication

Trang 8

Designing the shopping cart Web page

The application displays the items currently stored in the shopping cart, asshown in Figure 6-2

The shopping cart provides three buttons that the customer can click:

 Continue Shopping: Returns the customer to the first catalog page.

 Submit Order: Submits an order for the items that are in the shopping

cart

 Update Cart: Allows the customer to change the items in the cart The

customer can change the number of pounds in the Amount column andclick this button The shopping cart is redisplayed with the changedamounts If the number is changed to 0 (zero), the item is removed fromthe shopping cart

Notice that three items are currently in the cart Only two items wereselected in the products page shown in Figure 6-1 The first item shown

in the cart was stored in the cart previously; the two items were added

Designing the shipping form Web page

The application collects the information needed to process and ship theorder with the form shown in Figure 6-3

Figure 6-2:

Theshoppingcartdisplayed

by theshoppingcartapplication

Trang 9

I’ve simplified the shipping information form for this sample application

For your application, you will probably need to collect a billing name andaddress, as well as a shipping name and address as shown You also mightneed to collect a shipping method and other information

Designing the summary Web page

The application displays a summary of the order, so the customer can catchany errors and correct them, as shown in Figure 6-4

The summary page provides four buttons that the customer can click:

 Continue Shopping: Returns the customer to the first catalog page while

retaining the information in the order

 Edit Shipping Information: Returns the customer to the shipping

infor-mation form where the customer can change the shipping inforinfor-mation

as necessary

 Cancel Order: Cancels the order.

 Submit Order: Submits the order on the summary page The customer

is unable to make changes after this final submission

Figure 6-3:

Theshippinginformationformdisplayed bythe onlineordersapplication

Trang 10

The Food Shop must collect sales tax for customers living in Texas Thus, thesummary page shows sales tax If the address were in a different state, nosales tax would be charged.

The Food Shop charges shipping at 25 cents per item Thus, this three itemorder is charged 75 cents This simple amount was chosen to simplify theexample

Designing the confirmation page

The confirmation page is specific to your store It might simply be a repeat

of the summary page A confirmation page tells the customer that the orderhas been approved It might also tell the customer when the order will beshipped and often provides the order number that the customer can use totrack the order I don’t develop a specific confirmation or cancellation page

in this chapter I believe you can handle that without my help I just show you how to display it

Figure 6-4:

ThesummaryWeb Pagedisplayed bythe onlineordersapplication

Trang 11

Writing the code for the product information page

The catalog products page displays a list of product information Productsare displayed one page at a time Each page displays submit buttons for next,previous, and return to the index page

The code that creates the products page is in two separate files, as follows:

shopping_product_page.inc: Contains the code that defines the lookand feel of the Web page It produces a page that lists the products in atable Another file must be used in conjunction with this file to createthe page The other file contains the specific information for the page

fields_products_page.inc: Contains the specific information for theCatalog Products Web page When used with shopping_product_

page.inc, it displays the product information A different file with different products could be used with shopping_product_page.inc

(see Chapter 5) to create a page that displayed different products

I describe these two files in detail in Chapter 5 For this chapter, I add someelements to the Web page to allow online orders In this section, I describethe added elements only

Writing fields_products_page.inc

The fields_products_page.incfile is almost the same file that I describe

in Chapter 5 It builds two arrays that contain the specific information played in the product page The arrays are

dis-$page: Contains elements that are displayed at the top and the bottom

of the entire page

$table_heads: Contains elements that provide the headings for thetable that displays the products

The only difference between this file and the file of the same name in Chapter 5

is one additional element in the $table_headsarray The extra element isidentified in the explanation following Listing 6-1

The procedural and object-oriented files are the same

Trang 12

The products page has one additional column in the product informationrow The new column allows customers to enter the amount of the productthey want to order Therefore, the new column is added to the $table_heads

array The new column is the amount column

Writing shopping_product_page.inc

The shopping_product_page.incand shopping_product_page-oo.inc

files are very similar to the catalog_product_page.incand catalog_product_page-oo.incfiles in Chapter 5 However, a few additions arerequired that allow the customer to order online The file with the additions

is shown in Listing 6-2 I describe only the lines that are changed in this tion For a complete description of all the lines, see the section “Writing thecode for the products page” in Chapter 5

sec-The file for the procedural application is slightly different than the file for theobject-oriented application I first show the procedural file, and then I describethe changes needed to use the file with the object-oriented application

The file shown in Listing 6-2 defines the look and feel of the Product page

L ISTING 6-1: T HE F ILE T HAT C ONTAINS THE A RRAYS N EEDED FOR THE P RODUCT P AGE

<?php /* File: fields products_page.inc

* Desc: Defines the variables and builds the arrays needed

* to display the products page of the catalog.

*/

$page = array( “title” => “The Food Shop Catalog”,

“top” => “The Food Shop Catalog”,

“bottom” => “Send questions and comments

to admin@xFoodShop.com”, );

$table_heads = array(“catalog_number” => “Cat No”,

?>

L ISTING 6-2: T HE F ILE T HAT D EFINES THE P RODUCT P AGE

<?php /* File: shopping_product_page.inc

* Desc: Displays the products in the catalog for the

* selected category

*/

Trang 13

<input type=’submit’ name=’Cart’

value=’View Shopping Cart’>\n

echo “<div style=’margin-left: 1in; margin-right: 1in’>\n

<h1 style=’text-align: center’>{$page[‘top’]}</h1>\n

<p style=’font-size: 150%’><b>{$_POST[‘interest’]}</b>”; echo “<p align=’right’>($n_products products found)\n”;

echo “<table border=’0’ cellpadding=’5’ width=’100%’>\n”;

echo “<tr>”;

foreach($table_heads as $heading) {

echo “<th>$heading</th>”;

} echo “</tr>\n”;

echo “<form action=’$_SERVER[PHP_SELF]’ method=’POST’>\n”;

for($i=$n_start;$i<=$n_end;$i++) {

name=’item{$products[$i][‘catalog_number’]}’

value=’0’ size=’4’></td>\n”; #40 echo “</tr>”;

} echo “<input type=’hidden’ name=’n_end’ value=’$n_end’>\n”;

echo “<input type=’hidden’ name=’interest’

value=’$_POST[interest]’>\n”;

echo “<tr>

<td colspan=’2’> <input type=’submit’

value=’Select another category’></td>\n”;

echo “<td colspan=’2’ style=’text-align: center’>

<input type=’submit’ name=’Products’

value=’Add Items to Shopping Cart’>”; #51 echo “<td colspan=’2’ style=’text-align: right’>\n”;

if($n_end > $n_per_page) {

echo “<input type=’submit’ name=’Products’

value=’Previous’>\n”;

} if($n_end < $n_products)

Trang 14

The numbers in the following explanation refer to the line numbers in Listing6-2 I discuss only the elements added to the file in this chapter For informa-tion about the original file, see the discussion that follows Listing 5-4.

#11 Lines 11 to 15 add the View Shopping Cart button in the upper-rightcorner of the products page The button displays the current con-tents of the shopping cart

#38 Lines 38 to 40 add an input text field to each item where customerscan enter an amount to purchase The name of the field is built usingthe catalog number of the product For instance, the name of the textfield might be item11or item4002 The default value is 0 (zero) Thecustomer can change the value to the desired quantity The name ofthe field is passed in the $_POSTarray, along with the quantity, wherethe processing program can obtain the catalog number from the fieldname

#49 Lines 49 through 51 add an extra button named Products to the uct page, which is labeled Add Items to Shopping Cart

prod-Changing shopping_product_page.inc for use with the object-oriented application

The code in Listing 6-2 displays the products Web page when used with theprocedural code The file needs changes to work correctly with the object-oriented code

Lines 30 to 41 display the product information on each row In Listing 6-2, the information is displayed from an array named $products This array isbuilt from the information in the database in the ShopCatalog.phpscript,described in Listing 6-11 For the object-oriented application, these lines need to be changed to display the information from an object The object

is created in the script Orders-oo.php, shown in Listing 6-18

L ISTING6-2: (Continued)

{ echo “<input type=’submit’ name=’Products’

value=’Next $n_per_page’>\n”;

} echo “</td></form></tr></table>\n”;

echo “<p style=’font-size: 75%; text-align: center’>

{$page[‘bottom’]}\n”;

?>

</div></body></html>

Trang 15

To use the file with the object-oriented application, change lines 30 to 41 inListing 6-2 to the following lines and call the new file shopping_product_

As you can see, the variables are changed from arrays ($products[$i]

[‘name’]) to objects ($all[$i]->name’)

Writing the code for the shopping cart Web pageThe shopping cart page displays the items currently stored in the shoppingcart The customer can change the quantity ordered The customer can return

to the catalog to add more items or can submit the order

In this chapter, the shopping cart is not implemented the same way in theprocedural code and the object-oriented code To show both methods, Iimplemented the shopping cart by storing the items in the MySQL table inthe procedural code, but stored the items in a SESSIONvariable in the object-oriented code As a result, the code that displays the Web pages is slightlydifferent The following sections show the code for both methods

Writing the shopping cart Web page files: The procedural method

The code that creates the shopping cart page is in two separate files, as follows:

table_page.inc: Contains the code that defines the look and feel of theWeb page It produces a page that lists the products in a table Anotherfile must be used in conjunction with this file to create the page Theother file contains the specific information for the page

fields_cart.inc: Contains the specific information for the shoppingcart Web page When used with table_page.inc, it displays the itemsstored in the shopping cart

Trang 16

Writing fields_cart.incListing 6-3 shows the file that defines the variables for the shopping cart Webpage.

L ISTING 6-3: T HE F ILE T HAT C ONTAINS THE V ARIABLES FOR THE S HOPPING C ART

<?php /* File: fields_cart.inc

* Desc: Provides the information needed to display the

* cart.

*/

$page = array(“title” => “The Food Shop Shopping Cart”,

“top” => “The Food Shop”,

“top2” => “Shopping Cart”,

“bottom” => “Send questions or problems to

<a href=’ShopCatalog.php’>Continue Shopping</a>\n”; exit();

}

while($row = mysqli_fetch_assoc($result)) #29 {

foreach($row as $field => $value) {

if($field != “order_number”) {

$items[$n][$field]=$value;

if($field == “catalog_number”) {

$sql_2 = “SELECT name,type FROM food WHERE

catalog_number = ‘$row[catalog_number]’”;

$result2 = mysqli_query($cxn,$sql_2)

or die(“sql_2: “.mysqli_error($cxn));

Trang 17

The line numbers called out in Listing 6-2 correspond to the numbered nations in the following bullets:

expla-#14 Retrieves the order number from a session variable The ordernumber was stored in the session variable when the order was stored

in the database, when the user clicked the Add Items to ShoppingCart button The order number identifies this order in the database

#16 Lines 16 to 20 retrieve all the items from the order_itemtable in thedatabase (In other words, these lines retrieve all the items currentlystored in the shopping cart.)

#21 Sets $n_rowsto the number of items found in the database for thisorder

#22 Starts an ifblock that displays a message and a link when there are

no items in the database for the specified order number

#28 Sets a counter for the number of items

#29 Starts a whileloop that creates an array named $itemsthat containsall the information about the items The food name is retrieved fromthe catalog and added to the array

Writing table_page.incListing 6-4 shows the file that defines the look and feel of the shopping cartWeb page

$row = mysqli_fetch_row($result2);

$items[$n][“name”]=$row[0].” “.$row[1];

} } }

*Desc: Defines an HTML page that displays items in a

* table of items with prices A column named

* quantity and a column named price are multiplied

* together to get the item total price The item

* totals are summed.

*/

Trang 18

Order Number: $table_name<hr>\n”;

echo “<table border = ‘0’ style=’width: 100%’>\n”;

echo “<form action=’$_SERVER[PHP_SELF]’ method=’POST’>”; echo “<tr>”;

foreach($table_headers as $header) {

echo “<th>$header</th>\n”;

} echo “</tr>”;

echo “<tr><td colspan=’6’><hr></td></tr>\n”;

{ echo “<tr>”;

echo “<td style=’text-align: center; width: 20%’>

<input type=’text’ name=’quantity[]’

<tr><td colspan=’2’ style=’text-align: left’>

<input type=’submit’ name=’Cart’

value=’Continue Shopping’></td>

<td colspan=’2’ style=’text-align: center’>

<input type=’submit’ name=’Cart’

value=’Submit Order’></td>

<td colspan=’2’ style=’text-align: right’>

<input type=’submit’ name=’Cart’

value=’Update Cart’></td>

</tr></table></form></body></html>

Trang 19

The numbered items in the following list refer to the line numbers in Listing 6-4:

#25 Starts a forloop that loops through the $itemsarray, displayingeach row in the shopping cart Web page The loop ends on line 45

#27 Lines 27 to 39 display each item in the row from the current

$itemelement The price is formatted as a dollar amount

#40 Lines 40 to 43 display the total price Line 40 computes the totalcost, by computing price ×quantity Line 41 formats the totalcost as a dollar amount Line 42 to 43 display the line in theshopping cart Web page

#44 Sums the item total to accumulate a total for the cart

#48 Lines 48 to the end are HTML code that display the shopping carttotal and the submit buttons

Writing the shopping cart Web page files: The object-oriented method

The code that creates the shopping cart page is in two separate files, as follows:

table_page-oo.inc: Contains the code that defines the look and feel

of the Web page It produces a page that lists the products in a table

Another file must be used in conjunction with this file to create the page The other file contains the specific information for the page

fields_cart-oo.inc: Contains the specific information for the ping cart Web page When used with table_page-oo.inc, it displaysthe items stored in the shopping cart

shop-Writing fields_cart-oo.incListing 6-5 shows the file that defines the variables for the shopping cart Webpage

L ISTING 6-5: T HE F ILE T HAT C ONTAINS THE V ARIABLES FOR THE S HOPPING C ART

<?php /* File: fields_cart-oo.inc

* Desc: Builds the arrays needed to display the shopping

* cart.

*/

$page = array(“title” => “Shopping Cart”,

“top” => “The Food Shop”,

“top2” => “Shopping Cart”,

“bottom” => “Send questions or problems

Trang 20

Writing table-page-oo.incListing 6-6 shows the file that defines the variables for the shopping cart Webpage.

L ISTING 6-6: T HE F ILE T HAT D ISPLAYS THE S HOPPING C ART

<?php /*File: table_page-oo.inc

*Desc: Defines an HTML page that displays items in a

* table of items with prices A column named

* quantity and a column named price are multiplied

* together to get the item total price The item

* totals are summed.

echo “<form action=’$_SERVER[PHP_SELF]’ method=’POST’>”;

{ echo “<tr>”;

foreach($table_headers as $header) {

echo “<th>$header</th>\n”;

} echo “</tr>”;

echo “<tr><td colspan=’6’><hr></td></tr>\n”;

for($i=0;$i<sizeof($this->items);$i++) #26 {

echo “<td width=’20%’ style=’text-align: center’>

<input size=’4’ type=’text’ name=’item$cat_no’ value=’”.$this->items[$i]->getQuantity().

number_format($total,2).”</td>\n”;

@$order_total = $order_total + $total;

Trang 21

The following numbers refer to the line numbers in Listing 6-5:

#17 Begins an ifblock that executes if there are one or more items in theshopping cart The variable $itemsis an array of item objects, stored

in the ShoppingCartclass, which I discuss later in this chapter The

ShoppingCartclass is created in the orders application script The

ifblock displays the shopping cart Web page The ifblock ends online 65

#26 Begins a forloop that loops through the $itemsarray and plays the information for each item on the Web page The for

dis-loop ends on line 48

#30 Lines 30 to 33 get some information using a catalogobject Forinstance, line 33 gets the name of the item by using the getName

method in the Catalogclass Lines 34 to 35 display the mation obtained

infor-#44 Lines 43 to 44 accumulate the total for the shopping cart

#49 Lines 49 through the end display the shopping cart total andthe shopping cart submit buttons

<input type=’submit’

value=’Continue Shopping’></td>\n”;

echo “ <td colspan=’2’ style=’text-align: center’>

<input type=’submit’ name=’Ship’

value=’Submit Order’></td>\n”;

echo “ <td colspan=’2’ style=’text-align: right’>

<input type=’submit’ name=’Cart’

echo “<tr><td colspan=’5’ style=’text-align: left’>

Trang 22

#66 Begins an elseblock that executes when no items are stored in theshopping cart The block displays a button that returns the customer

to the catalog category page

Writing the code for the shipping information form

The shipping information form collects the information needed to ship theproduct It collects name, address, phone number, and other information.The code that displays the form is in two separate files, as follows:

single_form.inc: Contains the code that defines the look and feel ofthe Web form You must use another file in conjunction with this file tocreate the Web form The other file contains the specific informationsuch as the field names

fields_ship_info.inc: Contains the arrays and variables that areused by single_form.incto display the shipping information Webform

Writing fields_ship_info.inc

The fields_ship_info.incfile provides the information needed to displaythe shipping information Web form The file shown in Listing 6-7 defines sixarrays that contain the specific information displayed in the shipping infor-mation form The arrays are

$page: Contains elements that are displayed at the top and the bottom

of the entire page

$ship_info: Contains elements that provide the field names and labelsfor the shipping information form For instance, one field name is email.The associated label that displays by the field in the form is EmailAddress

$cc_types: Contains elements that provide the types of credit cards theform accepts The credit card types are displayed in a drop-down list inthe form

$length: Contains the lengths that are allowed for each field in the form

$elements: Contains elements that are displayed at the top and bottom ofthe form This array contains only text to display on the submit button

$months: Contains the months of the year The months are displayed in

a drop-down list for the credit card expiration date

In addition, the file sets a variable that contains the current date and severalvariables that contains the shipping information currently stored in the data-base, which is displayed in the fields of the form

Ngày đăng: 12/08/2014, 21:21

TỪ KHÓA LIÊN QUAN