Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
PHP Programming With MySQL Second Edition.doc
Скачиваний:
0
Добавлен:
01.05.2025
Размер:
43.07 Mб
Скачать

Introduction to Object-Oriented Programming

class. A particular instance of an object inherits its methods and

properties from a class—that is, it takes on the characteristics of

the class on which it is based. The BankAccount object, for instance,

would inherit all of the methods and properties of the BankAccount

class. As another example, when you create a word-processing docu-

ment, which is a type of object, it usually inherits the properties of a

template on which it is based. The template is a type of class, and the

document inherits characteristics of the template, such as font size,

line spacing, and boilerplate text. In the same manner, programs that

Include instances of objects inherit the object’s functionality.

In this chapter, you will create the Web site for an online order form

In an online store application. The application includes information

about each store and a custom inventory for each store. The primary

store you will use is Gosselin’s Gourmet Coffee, which sells various

blends of coffee beans. The purpose of the Web site is to demonstrate

code reuse with classes. As you progress through this chapter, you

will develop a class named OnlineStore that handles the functional-

Ity of building a working online store. Online store classes are very

popular with PHP development because of the many Web sites that

allow visitors to purchase items. Rather than recreating the same

functionality for each online store, you can much more easily develop

the Web site by reusing an existing online store class. As you create

the OnlineStore class, notice that its functionality has nothing to do

with Gosselin’s Gourmet Coffee or coffee beans. Instead, the code is

generic enough that it can be used with any Web site that sells prod-

ucts, provided the pages in the site and the associated database con-

form to the requirements of the class.

First, you create the database and tables that store the online store

Information and products. The OnlineStore class requires that store

Information is stored in a table containing six fields: storeId, name,

description, welcome, css_file, and email_address. The storeID

field is the primary key and consists of a unique text field. For exam-

ple, the primary key for Gosselin’s Gourmet Coffee is COFFEE. The

OnlineStore class also requires that product information is stored in

a table containing five fields: productID, storeID, name, description,

and price. The productID field is the primary key and consists of a

unique text field. For example, the primary key for the first product

for Gosselin’s Gourmet Coffee is COFFEE001. The storeID stores the

unique ID number for the store that sells the product. To keep things

simple, the OnlineStore class does not store customer or payment

Information. Instead, the class simply uses session iDs to keep track

of each user’s shopping cart.

Next, you create a database named online_stores along with two

tables: store_info, to contain configuration information for each

Class names

in traditional

object-ori-

ented pro-

gramming

usually begin with an

uppercase letter. This

convention is also

followed in PHP.

561


CHAPTER 10

Developing Object-Oriented PHP

store, and inventory, to contain product information. Your Chapter

directory for Chapter 10 contains two text files, store_info.txt and

inventory.txt, which contain store and product information to load

into each database table.

To create the Online Stores database:

562

1.

Log in to MySQL Monitor with the MySQL user name and

password you created in Chapter 7.

Enter the following command to create a database named

online_stores:

mysql> CREATE DATABASE online_stores;[ENTER

]

2.

3.

After you see the “Query OK” message, enter the following

command to select the online_stores database:

mysql> USE online_stores;[ENTER

]

4.

Enter the following command to create the store_info table:

mysql> CREATE TABLE store_info (storeID VARCHAR(10)

PRIMARY KEY,[ENTER ]

-> name VARCHAR(50), description VARCHAR(200),

welcome TEXT,[ENTER ]

-> css_file VARCHAR(250), email_address

VARCHAR(100));[ENTER ]

5.

After you see the “Query OK” message, enter a LOAD DATA

statement that inserts records into the store_info table from

the store_info.txt file in your Chapter directory for Chapter

10. Replace path with the path to your Chapter directory for

Chapter 10.

mysql> LOAD DATA INFILE 'path/store_info.txt'[ENTER

-> INTO TABLE store_info;[ENTER ]

]

6.

Enter the following command to create the inventory table:

mysql> CREATE TABLE inventory (storeID

varchar(10),[ENTER ]

-> productID VARCHAR(10) PRIMARY KEY,[ENTER ]

-> name VARCHAR(100), description VARCHAR(200),

price FLOAT);[ENTER ]

7.

After you see the “Query OK” message, enter a LOAD DATA

statement that inserts records into the inventory table from

the inventory.txt file in your Chapter directory for Chapter

10. Replace path with the path to your Chapter directory for

Chapter 10.

mysql> LOAD DATA INFILE 'path/inventory.txt'[ENTER

-> INTO TABLE inventory;[ENTER ]

]


Using Objects in PHP Scripts

8.

Type exit or quit and press Enter to log out of MySQL

Monitor.

Short Quiz

1.

2.

3.

4.

Discuss the benefits of object-oriented programming.

Explain how objects can be shared by multiple programming

languages such as PHP, C++, and Visual Basic.

Identify three benefits of encapsulating code.

Define the term “instance of a class.”

563

Using Objects in PHP Scripts

Up to this point, all of the PHP scripts you have written contained

procedural statements that did not rely on objects. Many of the

skills you have learned so far will help you construct object-oriented

programs. However, object-oriented techniques will help you build

more extensible code that is easier to reuse, modify, and enhance. In

this section, you will learn how to work with database connections

as objects to help you understand how to use objects in your scripts.

Then, you will learn how to define your own custom classes.

Before you begin working with database connections as objects, you

first need to understand a few basics of how to work with objects in

PHP. You declare an object in PHP by using the new operator with a

class constructor. A class constructor is a special function with the

same name as its class; it is called automatically when an object from

the class is instantiated. For example, the class constructor for the

BankAccount class is BankAccount(). The syntax for instantiating an

object is as follows:

$ObjectName = new ClassName();

The identifiers you use for an object name must follow the same rules

as identifiers for variables: They must begin with a dollar sign, can

include numbers or an underscore (but not as the first character after

the dollar sign), cannot include spaces, and are case sensitive. The fol-

lowing statement instantiates an object named $Checking from the

BankAccount class:

$Checking = new BankAccount();

CHAPTER 10

Developing Object-Oriented PHP

Class constructors are primarily used to initialize properties when an

object is first instantiated. For this reason, you can pass arguments

to many constructor functions. For example, the BankAccount class

might require you to pass the account number as a parameter, as

follows:

564

$Checking = new BankAccount(01234587);

After you instantiate an object, you use the combination of a hyphen

and a greater-than symbol (->) to access the methods and properties

contained in the object. Together, these two characters are referred to

as member selection notation. Using member selection notation is

similar to using an operator in that you append one or more charac-

ters (in this case, ->) to an object, followed by the name of a method

or property. With methods, you must also include a set of parenthe-

ses at the end of the method name, just as you would with functions.

Like functions, methods can also accept arguments.

The following statements demonstrate how to call two methods,

getBalance() and getCheckAmount(), from the $Checking object.

The getBalance() method does not require any arguments, whereas

the getCheckAmount() method requires an argument containing the

check number.

$Checking->getBalance();

$CheckNumber = 1022;

$Checking->getCheckAmount($CheckNumber);

The

printf()

function,

which allows

you to format

variables in an output

string, is described in

Appendix C. In this exam-

ple, the format specifier

%.2f causes the balance

to be displayed as a float-

ing-point number (f) with

two digits (specified by

the 2) after the decimal

point.

To access property values in an object, you do not include parenthe-

ses at the end of the property name, as you do with functions and

methods, nor do you include a dollar sign before the property name.

For example, the following statements update and display the value in

a property named $Balance in the $Checking object:

$CheckAmount = 124.75;

$Checking->Balance = $Checking->Balance + $CheckAmount;

printf("<p>Your updated checking account balance is

$%.2f.</p>", $Checking->Balance);

Next, you start creating the GosselinGourmetCoffee.php script,

which displays the coffee products available for purchase. The first

version of the script simply queries the database and displays a table

with the product information. Later in this chapter, you will modify

the script so it uses the OnlineStore class.

To create the GosselinGourmetCoffee.php script:

1.

Create a new document in your text editor and type the

<!DOCTYPE> declaration, <html> element, header informa-

tion, and <body> element. Use the strict DTD and “Gosselin’s

Gourmet Coffee” as the content of the <title> element.


Using Objects in PHP Scripts

2.

Add the following text and elements to the document body:

<h1>Gosselin's Gourmet Coffee</h1>

<h2>Description goes here</h2>

<p>Welcome message goes here</p>

<p>Inventory goes here</p>

3.

Save the document as GosselinGourmetCoffee.php in the

Chapter directory for Chapter 10 and upload the document to

the Web server.

Open the GosselinGourmetCoffee.php file in

your Web browser by entering the following URL:

http://<yourserver>/PHP_Projects/Chapter.10/Chapter/

GosselinGourmetCoffee.php. Your Web browser should look

like Figure 10-3.

4.

At this point,

the file has no

PHP code

sections.

Normally, a

file like this would be

saved with an .html exten-

sion. You save it with a

.php extension because

you will add PHP code

later in the chapter.

565

Figure 10-3

5.

The Gosselin’s Gourmet Coffee Web page

Close your Web browser window.

Working with Database Connections as Objects

PHP allows you to connect to and manipulate MySQL and other

types of databases using either procedural statements or object-ori-

ented techniques. Although you should not notice any performance

issues when using procedural statements or object-oriented tech-

niques to access MySQL databases, you can expect object-oriented

techniques to become the preferred method as PHP continues to

evolve. For this reason, you should get used to the object-oriented

method of accessing MySQL databases. As mentioned in Chapter

8, the mysqli package is the object-oriented equivalent of the mysql

package. The mysqli package will be used throughout this chapter.

You access MySQL database connections as objects by instantiat-

ing an object from the mysqli class. The mysqli class contains


CHAPTER 10

Developing Object-Oriented PHP

566

methods and properties that have the same functionality as the

procedural MySQL database connection statements you have used

so far. For example, the equivalent of the mysql_query() function

is a method named query() in the mysqli class, and the equiva-

lent of the mysql_affected_rows() function is a property named

affected_rows in the mysqli class. Next, you will learn how to

instantiate and close a MySQL database connection object.

Instantiating and Closing a MySQL Database Object

In Chapter 8, you learned how to use the mysql_connect() function

to open a connection to a MySQL database server. When connecting

to the MySQL database server using object-oriented techniques, you

instantiate an object from the mysqli class. You pass to the mysqli

class the same host, user, password, and database arguments that

you pass to the mysql_connect() and mysql_select_db() functions.

For example, the following statements use the mysql_connect() and

mysql_select_db() functions to connect to a MySQL database server:

$DBConnect = mysql_connect("php_db", "dongosselin",

"rosebud");

mysql_select_db("real_estate", $DBConnect);

You can

use the

select_db()

method of the

mysqli

object to select a

different database.

In comparison, you use the following statement to connect to the

MySQL database server using a mysqli object:

$DBConnect = new mysqli("php_db", "dongosselin",

"rosebud", "real_estate");

The preceding statement uses the mysqli() constructor function to

instantiate a mysqli class object named $DBConnect.

Instead of using the mysql_close() function to explicitly close the

database connection when you finish working with it, you call the

close() method of the mysqli class. For example, the following state-

ment closes the database connection represented by the $DBConnect

object (remember that $DBConnect is an object of the mysqli class):

$DBConnect->close();

To add statements to the GosselinGourmetCoffee.php script that

instantiate and close a database connection to the MySQL database

server using a mysqli object:

1.

Create a new document in your text editor with the following

script section:

<?php

?>

2.

Add the following statements to the script section to connect

to the database server using a mysqli object. The code uses


Using Objects in PHP Scripts

an if statement to store an error message in the $ErrorMsgs

array if there was a connection error. Be sure to replace host,

user, and password with your MySQL server name, user

name, and password.

$ErrorMsgs = array();

$DBConnect = new mysqli("host", "user", "password",

"online_store");

if (!$DBConnect)

$ErrorMsgs[] = "The database server is not

available.";

567

3.

Save the document as inc_OnlineStoreDB.php in the Chap-

ter directory for Chapter 10.

Return to the GosselinGourmetCoffee.php script in your

text editor.

Add the following script section to the start of the document,

before the <!DOCTYPE> tag:

<?php

require_once("inc_OnlineStoreDB.php");

?>

4.

5.

6.

Add the following script section to the body of the document,

immediately before the closing </body> tag:

<?php

if (count($ErrorMsgs)) {

foreach ($ErrorMsgs as $Msg)

echo "<p>" . $Msg . "</p>\n";

}

else

echo "<p>Successfully connected to the

database.<p>\n";

?>

7.

Add the following script section to the end of the document

to close the database connection:

<?php

$DBConnect->close();

?>

8.

Save the GosselinGourmetCoffee.php file and then upload

inc_OnlineStoreDB.php and GosselinGourmetCoffee.php to

the Web server.

Open the GosselinGourmetCoffee.php script in your Web

browser by entering the following URL: http://<yourserver>/

PHP_Projects/Chapter.10/Chapter/GosselinGourmetCoffee.

php. You should see the message about successfully connect-

ing to the database server (see Figure 10-4).

9.


CHAPTER 10

Developing Object-Oriented PHP

568

Figure 10-4

Gosselin’s Gourmet Coffee Web page after connecting to the database server

10.

Close your Web browser window.

Handling MySQL Errors

When you use procedural syntax to connect to the MySQL database

server, the mysql_connect() function returns a value of FALSE if

the database connection attempt fails. However, when you use the

mysqli() constructor function to instantiate a new database object

from the mysqli class, an object is instantiated even if the database

connection fails. That means the if (!$DBConnect) statement in

inc_OnlineStoreDB.php would always evaluate to FALSE. To deter-

mine if the database connection attempt failed when working with

the mysqli object, you need to use the connect_errno data member

of the mysqli object to retrieve the error code from the last connec-

tion attempt. A value of 0 indicates no error, or a successful connec-

tion. A nonzero value indicates that the connection attempt failed, as

in the following example:

$DBConnect = @new mysqli("php_db", "dgosselin",

"rosebud");

if ($DBConnect->connect_errno) {

echo "<p>Unable to connect to the database server.</p>"

. "<p>Error code " . $DBConnect->connect_errno

. ": " . $DBConnect->connect_error . "</p>\n";

}

else {

// code that executes if the database connection attempt

// succeeded

}

Notice in the preceding example that the first statement, which

instantiates the database connection object, uses the error control

operator, @, to suppress error messages. Recall that you can place the


Using Objects in PHP Scripts

error control operator before any expression to suppress error mes-

sages. The error control operator in the preceding example is placed

before the new operator because it begins the expression that instanti-

ates the database connection object.

It is important to note that the mysqli class members connect_errno,

connect_error, errno, and error are data members, or variables, of

the database connection object. In the procedural mysql package, the

corresponding mysql_errno() and mysql_error() are functions.

Most of the methods of the mysqli class return values of TRUE

or FALSE, depending on whether the operation was successful.

Therefore, for any methods of the mysqli class that fail (as indi-

cated by a return value of FALSE), you can use the same if...else

structure as you did in Chapter 8. For example, the following state-

ment checks the return value of the select_db() method to display

an error message if a value of FALSE was returned. Notice that the

object-oriented $DBConnect->errno and $DBConnect->error data

members are used in place of the procedural mysql_errno() and

mysql_error() functions, and that the statement which calls the

select_db() method also uses the error control operator to suppress

error messages.

$DBName = "vehicle_fleet";

$Result = @$DBConnect->select_db($DBName);

if ($Result === FALSE)

echo "<p>Unable to select the database. " .

"Error code " . $DBConnect->errno .

": " . $DBConnect->error . "</p>\n";

else {

// Code to execute if database selected successfully.

}

569

To add MySQL error-checking functionality to the

GosselinGourmetCoffee.php script:

1.

Return to the inc_OnlineStoreDB.php script in your text

editor.

Add the error control operator (@) before the new keyword, as

follows:

$DBConnect = @new mysqli("host", "user", "password",

"online_stores");

2.

3.

Replace the if statement with the following if statement that

checks the value of the $DBConnect object’s connect_errno

data member to see if it is nonzero, indicating a connection

error:


CHAPTER 10

Developing Object-Oriented PHP

if ($DBConnect->connect_errno)

$ErrorMsgs[] = "Unable to connect to the

database server." .

" Error code " . $DBConnect->connect_errno

. ": " . $DBConnect->connect_error;

4.

570

5.

Save the inc_OnlineStoreDB.php file.

Return to the GosselinGourmetCoffee.php script in your

text editor.

Remove the following two lines of code that display a message

if there were no errors:

else

echo "<p>Successfully connected to the database

.<p>\n";

6.

7.

Replace the $DBConnect->close(); statement with the fol-

lowing if statement, which verifies that there are no connect

errors before attempting to close the connection:

if (!$DBConnect->connect_error)

$DBConnect->close();

8.

Save the GosselinGourmetCoffee.php file and then upload

inc_OnlineStoreDB.php and GosselinGourmetCoffee.php to

the Web server.

Open the GosselinGourmetCoffee.php script in your Web

browser by entering the following URL: http://<yourserver>/

PHP_Projects/Chapter.10/Chapter/GosselinGourmetCoffee.

php. The Web page should look the same as it did before

you added the MySQL error-checking functionality, with

the exception of the “Successfully connected to the database

server” message, which no longer appears.

Close your Web browser window.

9.

10.

Executing SQL Statements

Recall that you send SQL statements to MySQL with procedural syn-

tax by using the mysql_query() function. With a mysqli object, you

use the query() method of the mysqli class. The query() method

accepts a single argument representing the SQL statement you

want to send to the MySQL database server. For queries that return

results using procedural syntax, you use the mysql_fetch_row()

function to return the fields in the current row of a resultset into an

indexed array. You use the mysql_fetch_assoc() function to return

the fields in the current row of a resultset into an associative array.

In comparison, with a mysqli object, you call the fetch_row() and

fetch_assoc() methods of the mysqli class.


Using Objects in PHP Scripts

The following code demonstrates how to use a mysqli object to

execute a query that returns all the records from the company_cars

table of the vehicle_fleet database. The code builds a table and uses

the fetch_row() method to return the fields in the current row into

an indexed array. The code is very similar to examples you have seen

in the past few chapters. The biggest difference is that the object-

oriented query() method, which is the equivalent of the procedural

mysql_query() function, only returns TRUE for a successful query and

FALSE for a failed query.

To retrieve the results, you call the use_result() method, which

returns a mysqli_result object. You then call the fetch_row() and

fetch_array() methods of the mysqli_result object, just as you

called the procedural mysql_fetch_row() and mysql_fetch_array()

functions. One important difference is that the object-oriented

fetch_row() and fetch_array() methods return NULL if there

are no more results, while the procedural mysql_fetch_row() and

mysql_fetch_array() functions return FALSE.

$TableName = "company_cars";

$SQLstring = "SELECT * FROM $TableName";

$QueryResult = @$DBConnect->query($SQLstring);

if ($QueryResult === FALSE)

echo "<p>Unable to execute the query. " .

"Error code " . $DBConnect->errno .

": " . $DBConnect->error . "</p>\n";

else {

echo "<table width='100%' border='1'>\n";

echo "<tr><th>License</th><th>Make</th><th>Model</th>" .

"<th>Mileage</th><th>Year</th></tr>\n";

while (($Row = $QueryResult->fetch_row()) !== FALSE)

{

echo "<tr><td>{$Row[0]}</td>";

echo "<td>{$Row[1]}</td>";

echo "<td>{$Row[2]}</td>";

echo "<td align='right'>{$Row[3]}</td>";

echo "<td>{$Row[4]}</td></tr>\n";

}

echo "</table>\n";

}

571

You must be

sure to test

for NULL

and not

FALSE

when using the object-

oriented methods. If you

check for FALSE, your

code will be stuck in an

infinite loop.

To add code to the GosselinGourmetCoffee.php script that uses a

mysqli object query to retrieve product information from the coffee

table in the online_store database:

1.

Return to the GosselinGourmetCoffee.php script in your

text editor.

Remove the section of HTML code that displays the text

“Inventory goes here”.

2.


CHAPTER 10

Developing Object-Oriented PHP

3.

572

Add the following if statement above the statement that dis-

plays the database error messages. The if statement verifies

that there are no error messages before querying the database.

The first statement within the code block for the if statement

creates a SQL string, and the second statement uses mysqli

class syntax to perform the query. Recall that the storeID

value for Gosselin’s Gourmet Coffee is “COFFEE”.

if (count($ErrorMsgs)==0) {

$SQLstring = "SELECT * FROM inventory " .

"WHERE storeID='COFFEE'";

$QueryResult = $DBConnect->query($SQLstring);

if ($QueryResult === FALSE)

$ErrorMsgs[] = "<p>Unable to perform the

query. " .

"<p>Error code " . $DBConnect->errno .

": " . $DBConnect->error . "</p>\n";

}

4.

Add the following else clause to the if statement that dis-

plays the error messages. Within the else clause, you build a

table showing the items available from the online store.

else {

echo "<table width='100%'>\n";

echo "<tr><th>Product</th><th>Description</th>" .

"<th>Price Each</th></tr>\n";

while (($Row = $QueryResult->fetch_assoc()) !==

NULL) {

echo "<tr><td>" . htmlentities($Row['name']) .

"</td>\n";

echo "<td>" .

htmlentities($Row['description']) .

"</td>\n";

printf("<td>$%.2f</td></tr>\n", $Row['price']);

}

echo "</table>";

}

5.

Save the GosselinGourmetCoffee.php file and then upload it

to the Web server.

Open the GosselinGourmetCoffee.php script in your Web

browser by entering the following URL: http://<yourserver>/

PHP_Projects/Chapter.10/Chapter/GosselinGourmetCoffee.

php. You should see the table shown in Figure 10-5.

6.


Using Objects in PHP Scripts

573

Figure 10-5

7.

Gosselin’s Gourmet Coffee Web page displaying query results

Close your Web browser window.

Defining Custom PHP Classes

Classes were defined earlier in this chapter as the code, methods,

attributes, and other information that make up an object. In PHP,

classes more specifically refer to data structures that contain variables

along with functions for manipulating the variables. The term data

structure refers to a system for organizing data. Some of the data

structures you have already used include arrays, text files, and data-

base records. The functions and variables defined in a class are called

class members. Class variables are referred to as data members

or member variables, whereas class functions are referred to as

member functions or function members. To use the variables and

functions in a class, you instantiate an object by declaring the object

as a new instance of the class. After you instantiate an object, class

data members are referred to as properties of the object and class

member functions are referred to as methods of the object.

Classes are also referred to as user-defined data types or programmer-

defined data types. These terms can be somewhat misleading, however,

because they do not accurately reflect the fact that classes can contain

member functions. In addition, classes usually contain multiple data

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]