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

PHP & MySQL Everyday Apps for Dummies phần 6 pot

45 209 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

Tiêu đề Building Online Sales Applications
Chuyên ngành Computer Science and Web Development
Thể loại Sách hướng dẫn
Định dạng
Số trang 45
Dung lượng 900,3 KB

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

Nội dung

The block displays theshipping information form with the shipping information that is cur-rently stored in the database.. The following list of objectsreflects the tasks this application

Trang 1

#148 Lines 148 to 150 display the summary Web page.

#152 Begins an elseifblock that executes when the button is named Ship.This condition is true when the user clicks the Edit Shipping

Information button on the summary page The block displays theshipping information form with the shipping information that is cur-rently stored in the database

#157 Begins an elseifblock that executes when the user clicks a buttonnamed Final These buttons are displayed on the summary Web page

#159 Starts a switchstatement based on which Final button the userclicks

#161 Starts the caseblock that executes when the value of the Finalbutton is Continue Shopping The block runs the

ShopCatalog.phpscript, which displays the catalog indexpage

#164 Starts the caseblock that executes when the value of the Finalbutton is Cancel Order The block displays a cancellation Webpage, by including two files, and destroys the session Noticethat the two include statements have a comment mark (#) atthe beginning of the line These two statements are commentedout because the cancellation Web page isn’t provided in thischapter, in the interests of saving space You need to develop

a cancellation page that is specific to your order process

#171 Starts the caseblock that executes when the value of the Finalbutton is Submit Order The block sets the order status toSubmitted=’yes’

#177 Calls a function that processes the credit card information I

don’t provide this function because it depends on which creditcard processing company you use The company will provideyou with the information needed to write the function In gen-eral, the function sends the credit information to the companyand receives a code from them that either accepts or rejects thecredit charge Notice that the statement in the listing has a com-ment mark (#) at the beginning of the line so that it doesn’tactually execute It’s just there to show you a possible state-ment to use

#178 Calls a function that sends the order information to the person/

department responsible for filling and shipping the order Thisfunction depends on your internal procedures The functionmight send an e-mail notice to the shipping department, or yourprocess might be altogether different This statement is alsocommented out because I don’t provide the function

#179 Displays an order confirmation (or not accepted) Web page by

including two files The files are not provided, so the includestatements are commented out You need to write your ownfiles to include at this location

Trang 2

#181 Calls a function that sends an e-mail to the customer This

func-tion call is commented out, because I don’t provide the emailfunction You need to write a function that creates and sends ane-mail message specific to your business Sending an e-mail isshown in detail in Chapter 4

#182 Destroys the session The user can’t make any changes to the

order after clicking the Submit Order button on the summarypage

Building the Shopping Cart Application:

The Object-Oriented Approach

Object-oriented programming requires that you create and use objects to vide the functionality of the application You first identify the objects neededfor the application Then you write the classes that define the objects, includ-ing the methods that the application needs When the objects are ready, youwrite the application script that creates and uses the objects

pro-Developing the objects

The shopping cart application needs to display products from the catalog Itstores the customer’s choices in a shopping cart It stores the order shippinginformation and the items ordered in a database The following list of objectsreflects the tasks this application needs to perform:

Catalog: The Catalogclass returns and displays product information

as needed

Database: The application stores the product information in a database

The Databaseclass provides the container that stores the data

Item: The customer orders items The items are stored in the shoppingcart and stored in the order database The Itemclass stores andretrieves information about the item

ShoppingCart: The shopping cart holds the items currently selected

by the customer The customer can add items to and delete items fromthe cart

Order: The shipping and credit information for the order needs to

be associated with the items in the order The Orderclass stores andretrieves all the information about the order that is stored in the database

Trang 3

WebForm: A form is used to collect the shipping and credit informationfrom the customer The WebFormclass provides the form for the applica-tion It collects and processes the information typed by the customer.

WebPage: The WebPageclass displays a Web page that includes tion from PHP variables The WebPageclass is used frequently through-out this book whenever a Web page needs to be displayed

informa-Email: The application sends an e-mail to customers when they order,letting them know that the order has been accepted and other informa-tion about their orders The Emailclass contains and manages thee-mail message

I discuss the details for each class in the following sections

Writing the Catalog class

The Catalogclass maintains a connection to the database where the productinformation is stored The Catalogclass returns or displays product informa-tion as needed I develop the Catalogclass in Chapter 5 I add two additionalmethods to the class for the shopping cart application (Refer to Listing 5-7 forthe Catalogclass code.) I describe the new methods, getNameand getPrice,later in this section

The methods provided by the Catalogclass are:

 The constructor: Creates a connection to a MySQL database The

con-structor expects to be passed a filename of the file that contains thehostname, account name, and password necessary to access MySQL.The following statement creates a Databaseobject:

$db = new Database(“Vars.inc”);

useDatabase: Selects a database and stores the database name Themethod expects to be passed a database name It checks whether thedatabase exists and returns a message if the database doesn’t exist

getConnection: Returns the connection that is established and stored

in the constructor

getName: Returns the product name This method expects to be passed

a catalog number This method is added in this chapter The code isshown in Listing 6-14

getPrice: Returns the price This method expects to be passed a log number This method is added in this chapter The code is shown inListing 6-14

cata-The code for the getNameand getPricemethods is shown in Listing 6-14

Trang 4

The getName method

The getNamemethod returns the product name, formatted as type For instance, in this application, the method returns Delicious Apple

name-space-or Mandarin Orange

L ISTING 6-14: T HE N EW M ETHODS FOR THE C ATALOG C LASS function getName($catalog_number)

{ if(ereg(“[0-9]*”,$catalog_number)) {

$sql = “SELECT name,type FROM Food

WHERE catalog_number=’$catalog_number’”;

} else { throw new Exception(“$catalog_number is not a

catalog number.”);

exit();

} if(!$result = $this->connection->query($sql)) {

throw new Exception(mysqli_error($this->connection));

if(ereg(“[0-9]*”,$catalog_number)) {

$sql = “SELECT price FROM Food

WHERE catalog_number=’$catalog_number’”;

} else { throw new Exception(“$catalog_number is not a

catalog number.”);

exit();

} if(!$result = $this->connection->query($sql)) {

throw new Exception(mysqli_error($this->connection));

Trang 5

The method tests that the catalog number passed to it contains only bers For other applications, the catalog number might have a differentformat that contains letters or other characters The ifstatement needs totest the format of the catalog number in as much detail as possible.

num-If the catalog number has the correct format, an SQL query is built to selectthe needed information from the database The query is executed The infor-mation returned by the query is added to a string with the correct format.The formatted information is returned You can call the method as follows:

$product_name = $catalog->getName(“1004”);

where “1004”is the catalog number for the product

The getPrice method

The getPricemethod returns the product price An SQL query is built toselect the price from the database and executed The method returns theprice The syntax for calling the method is shown here:

$product_price = $catalog->getPrice($catalog_number);

Writing the Item class

The Itemclass is a fundamental class The customer orders items The itemobject stores and retrieves the information about an item that the customerselected

The code

Listing 6-15 contains the complete code for the Itemclass After the code ing you can find details about each method

Trang 6

list-L ISTING 6-15: T HE I TEM C LASS

<?php /* Name: Item.class

* Desc: Represents an item in the order.

*/

class Item {

if(is_string($cat_no) && is_numeric($quantity)) {

catalog number and quantity”);

} } function getCatalogNumber() {

return $this->catalog_number;

} function getQuantity() {

return $this->quantity;

} function getPrice() {

return $this->price;

} function getName() {

return $this->name;

} }

?>

Trang 7

The constructor

The constructor collects and stores the information for the item the catalognumber and the quantity are passed when a new Item is created The con-structor stores the catalog number and quantity in the Itemproperties Theconstructor retrieves the remaining two properties from the catalog databaseand stores them in the Itemproperties

An item is created as follows:

$item1 = new Item(5007,3)

getCatalogNumber, getQuantity, getPrice, getName

These methods return the specified item information The methods are used

as follows:

$price = getPrice();

Writing the ShoppingCart class

The shopping cart is a major component of the shopping cart application Itholds the items currently selected by the customer

The code

Listing 6-16 contains the complete code for the ShoppingCartclass I covereach method in detail after the code listing

Trang 8

L ISTING 6-16: T HE S HOPPING C ART C LASS

<?php /* Name: ShoppingCart.class

* Desc: Creates a shopping cart a structure that

* holds items.

*/

class ShoppingCart {

private $items = array();

private $message;

private $n_items = 0;

function construct() {

if(isset($_SESSION[‘items’])) {

return $this->items;

} function getMessage() {

return $this->message;

} function displayCart($file_fields,$file_page) {

include($file_fields);

include($file_page);

} function updateCart($new_array) {

if(is_array($new_array)) {

Continued

Trang 9

$message, is set to a string of text that shows the number of items in the cart.The object is created without passing any arguments, as follows:

$cart = new ShoppingCart();

When the shopping cart is created, either it is new and empty or it containsthe items stored for the session

addItem

The addItemmethod adds an item to the cart It expects to receive an itemobject It adds the item to the item array and stores the new array in the ses-sion variable This method also increments the number of items stored andupdates the message with the new number of items You use the method asfollows:

} }

?>

Trang 10

getAllItems, getMessage

The getAllItemsand getMessagemethods get the specified properties ThegetAllItemsmethod returns the array of item objects stored in the cartproperties The getMessagemethod returns the stored message Neithermethod expects an argument to be passed

displayCart

The displayCartmethod displays the shopping cart on a Web page Thenames of the files that provide the fields and define the page are passed tothe method You can use the methods as follows:

$cart = new ShoppingCart();

$cart->displayCart(“fields_cart-oo.inc”,”table_page.inc”);

updateCart

The updateCartmethod updates an existing cart It expects an array ing the information for all the items to be in the updated cart The methodreplaces the existing array of items with the a new array of items created fromthe information passed to the method

contain-The array passed to the method should contain keys in the format itemnnnn

where nnnnis the catalog number of an item The value is the quantity for theitem A sample array might contain the following:

Writing the Database class

The Databaseclass provides the connection to the database where the tomer information is stored I develop the Databaseclass in Chapter 3 SeeListing 3-4 for the Databaseclass code

Trang 11

cus-The methods provided by the Databaseclass are:

 The constructor: Creates a connection to a MySQL database The

con-structor expects to be passed a filename where the hostname, accountname, and password necessary to access MySQL are stored A Databaseobject is created with the following statement:

$db = new Database(“Vars.inc”);

useDatabase: Selects a database and stores the database name Themethod expects to be passed a database name It checks whether thedatabase exists and returns a message if the database doesn’t exist

getConnection: Returns the connection that is established and stored

in the constructor

Writing the Order class

The order contains all the information needed to complete the customer’spurchase It contains the shipping and credit information and the item infor-mation for each item ordered The order information is stored in a database

* Desc: Class that holds orders.

*/

class Order {

private $order_number;

Trang 12

$this->table = $table;

} else { throw new Exception(“$table is not a

valid table name.”);

} } function createOrder() {

$today = date(“Y-m-d”);

$sql = “INSERT INTO $this->table

(order_date) VALUES (‘$today’)”;

if($result = $this->cxn->query($sql)) {

$this->order_number = $this->cxn->insert_id;

$_SESSION[‘order_number’] = $this->order_number;

} else { throw new Exception(“Database is not available

Try again later”);

} } function getOrderNumber() {

return $this->order_number;

} function addCart(ShoppingCart $cart) {

foreach($cart->getAllItems() as $n => $item) {

($this->order_number,$cat_no,

$quantity,($n+1),$price)”;

Trang 13

L ISTING6-17: (Continued)

$result = $this->cxn->query($sql);

} } function selectOrder($order_number) {

if(is_int($order_number)) {

$this->order_number = $order_number;

} else { throw new Exception(“$order_number

is not an integer.”);

} } function getOrderInfo() {

$sql = “SELECT * FROM $this->table

WHERE order_number=’$this->order_number’”;

if($result = $this->cxn->query($sql)) {

return $result->fetch_assoc();

} else { throw new Exception(“Database is not available

Try again later”);

} } function getItemInfo() {

$sql = “SELECT item_number,catalog_number,quantity,price

FROM order_item WHERE order_number=’$this->order_number’”;

if($result = $this->cxn->query($sql)) {

$n=1;

while($row=$result->fetch_assoc()) {

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

Trang 14

return $item;

} else { throw new Exception(“Database is not available

Try again later”);

} } function updateOrderInfo($data) {

if(!is_array($data)) {

throw new Exception(“Data must be in an array.”);

exit();

}

$sql = “UPDATE $this->table SET “;

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

if(ereg(“ship”,$field) || $field == “phone”

|| $field == “email”) {

$data_array[] = “$field=’$value’”;

} }

$sql = implode($data_array,’,’);

$sql = “WHERE order_number=’$this->order_number’”;

if(!$result = $this->cxn->query($sql)) {

throw new Exception(“Database is not available

Try again later”);

} return true;

} function displayOrderSummary($field_info,$field_page) {

} } }

?>

Trang 15

The constructor

The constructor stores the information needed to connect to the database Itexpects to be passed a connection and a table name The connection is adatabase connection provided by a Databaseobject The constructor storesthe information in the Orderproperties

You can create an Orderobject as follows:

$db = new Database(“Vars.inc”);

$db->selectDatabase(“OnlineOrders”);

$order = new Order($db->getConnection(),”Customer_Order”);

createOrder

The createOrdermethod inserts a new order into the order database using

an SQL query Today’s date is stored The MySQL AUTO_INCREMENTfeaturecreates the order number The new order number is stored in the order prop-erty and in a session variable The method returns trueif the order is suc-cessfully created

selectOrder

The selectOrdermethod sets the order number in the Orderto the ordernumber passed to it Any information retrieved later from the database isretrieved based on the order number property

addCart

The addCartmethod adds all the items in a shopping cart to the order Themethod expects to be passed a ShoppingCartobject The method uses aforeachloop to loop through all the items in the shopping cart The informa-tion from each item object is used to build an SQL query that inserts the iteminto the order_itemtable

getOrderInfo

The getOrderInfomethod returns an associative array containing all theinformation from the customer_ordertable It includes the name andaddress, phone, date created, and other order-level information It creates anSQL SELECTquery that selects all the information No parameter is expected

getItemInfo

The getItemInfomethod returns a multidimensional array containing all theinformation for all the items in the order The information for each item in thearray includes all the fields from the order_itemtable in the database, plusthe product name retrieved from the catalog

Trang 16

The method executes a query that gets all the information from the order_

itemtable A whileloop processes each item row in turn A foreachloopruns for each row, adding each field to the array element resulting in a multi-dimensional array After the foreachloop finishes, the method retrieves theproduct name from the catalog and adds it to the array

updateOrderInfo

The updateOrderInfomethod updates the shipping information in the customer_ordertable of the database The method expects an array of ship-ping information, such as the $_POSTarray from the shipping informationform An SQL UPDATEquery is created from the data in the $dataarray

The query is built with an opening section and phrases for each field, such

as ship_name=John Smith Each update phrase is added to a new array,

$data_array After all fields have been processed and added to the newarray, the implodefunction is used to convert the array into a string suitablefor use in the query The WHEREclause is then added to the end of the query

The method can be used with a statement similar to the following:

Writing the WebForm class

The WebFormis used to display and process the shipping information form Icreate and explain the WebFormclass in Chapter 4 The class is shown inListing 4-6

The methods in the WebFormclass that the shopping cart application scriptuses are:

 The constructor: Stores the properties needed to display the form

cor-rectly Two files — an information file and a file that defines the look andfeel — are required The two filenames are passed when the WebFormobject is created and stored in two properties The data for the formfields can be passed, but can be left out and the form fields will be blank

You can create the object by using either of the following statements:

$form = new WebForm(“file1.inc”,”file2.inc”,$_POST);

$form = new WebForm(“file1.inc”,”file2.inc”);

Trang 17

displayForm: This method displays the form It extracts the data from the

$dataproperty where it is stored An @is used to suppress the error sages so that the form can be displayed without any data The form is dis-played by including the two files that define the form These two files candefine any type of form, with fields and elements you want to use For thisapplication, I use the files I describe earlier in this chapter — fields_ship_info-oo.incand single_form.inc— which define the shippinginformation form

mes-checkForBlanks: Checks each field in the form to see whether it tains information If the method finds invalid blank fields, it returns anarray containing the field names of the blank fields

con-verifyData: This method checks each field to ensure that the tion submitted in the field is in a reasonable format For instance, youknow that “hi you” is not a reasonable format for a zip code This methodchecks the information from specific fields against regular expressionsthat match the information allowed in that field If invalid data is found inany fields, the method returns an array containing messages that identifythe problems

informa-trimData, stripTagsFromData: A PHP function is applied to each value

in the $dataproperty The resulting values are stored in $data The trimfunction removes leading and trailing blanks from a string The strip_tagsfunction removes any HTML tags from the string, important forsecurity

Writing the WebPage class

I use the WebPageclass throughout this book whenever I need to display aWeb page The WebPageobject is a Web page that displays information inPHP variables, along with HTML code The code that defines the Web page is

in a separate file You include the file to display the Web page I develop andexplain the WebPageclass in Chapter 3 You can see the WebPageclass listing

in Listing 3-6

The WebPageclass includes the following methods:

 The constructor: Stores a filename and the data needed to display the

page Expects to be passed the filename of the file that contains the HTMLcode that defines the Web page It also expects to be passed an array con-taining any data that needs to be displayed in the page A WebPage objectcan be created with a statement similar to the following:

$web_page1 = new WebPage(“define_page.inc”,$data);

displayPage: Displays the Web page The method extracts the tion in the $dataarray and includes the HTML file

Trang 18

informa-Writing the Email Class

After a customer successfully submits an order, the application sends a firmation e-mail message to the e-mail address provided by the customer

con-(You can find out about the Emailclass in Chapter 4, and the code is shown

Table 6-3 Buttons Displayed by the Shopping Cart Application

Select a Category Catalog index ProductsContinue Shopping Catalog Product (No name)Continue Shopping Shopping Cart (No name)

Add Items to Cart Catalog Product Cart

Continue Shipping information form Summary

Trang 19

The following text gives a general overview of the application script:

if (Button name = Products) Display catalog products page for the category selected elseif (Button name = Cart)

if (Button = Update Cart)

1 Update items and quantities in shopping cart.

2 Display cart.

elseif (Button = Add Items to Cart)

1 Add the selected items to shopping cart.

2 Display shopping cart.

elseif (Button name = Ship)

1 If current order exists, get order number from the session variable If not, create a new order.

2 Display shipping information form.

elseif (Button name = Summary)

1 Check form information for blanks If blanks found, redisplay form with error message.

2 Check form information for correct format If invalid information found, redisplay form with error message.

3 Add shipping information from form to database.

4 Add the items in the shopping cart to the database.

5 Display summary form.

elseif (Button name = Final)

if (Button = “Submit Order”)

1 Update order status to submitted.

2 Process credit card information.

3 Submit order to be filled and shipped.

4 Send confirmation email to customer.

5 Display confirmation Web page.

elseif (Button = “Cancel Order”)

1 Update order status to cancelled.

2 Display cancellation Web page.

3 Destroy session.

else Display catalog index page

The application program creates objects and uses their methods to performthe tasks that I describe in the preceding application overview You see theapplication program script in Listing 6-18

L ISTING 6-18: T HE S HOPPING C ART A PPLICATION S CRIPT

<?php /* Program: Orders-oo.php

* Desc: Handles all functions of the Online Orders

* application The submit button name is tested

* to determine which section of the program

* executes.

*/

require_once(“Item.class”);

require_once(“Catalog.class”);

Trang 20

$catalog = new Catalog(“Vars.inc”);

$catalog->selectCatalog(“OnlineOrders”);

$catalog->displayAllofType($_POST[‘interest’],2);

} catch(Exception $e) {

echo $e->getMessage();

exit();

} }

{

$cart = new ShoppingCart();

{ try {

$cart->updateCart($_POST);

} catch(Exception $e) {

echo $e->getMessage();

exit();

} }

{

{ if(ereg(“item”,$field) && $value > 0) {

try {

$item = new Item($cat_no,$value);

$cart->addItem($item);

} catch(Exception $e) {

echo $e->getMessage();

exit();

}

Continued

Trang 21

L ISTING6-18: (Continued)

} } } try {

$cart->displayCart(“fields_cart-oo.inc”,

} catch(Exception $e) {

echo $e->getMessage();

exit();

} }

{ try {

echo $e->getMessage();

exit();

} }

{ try {

$form = new WebForm(“single_form.inc”,

“fields_ship_info-oo.inc”,$_POST);

$blanks = $form->checkForBlanks();

} catch(Exception $e)

Trang 22

{ echo $e->getMessage();

}

{

$GLOBALS[‘message’] = “The following required fields

were blank Please enter the required information: “;

foreach($blanks as $value) {

$errors = $form->verifyData();

} catch(Exception $e) {

echo $e->getMessage();

} if(is_array($errors)) {

$GLOBALS[‘message’] = “”;

foreach($errors as $value) {

$db->useDatabase(“OnlineOrders”);

$order = new Order($db->getConnection(),”Customer_Order”);

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

TỪ KHÓA LIÊN QUAN