BUY THIS BOOK
Add to Cart

Print Book $44.95


Add to Cart

PDF $35.99

Safari Books Online

What is this?

Add to UK Cart

Print Book £31.95

What is this?

Looking to Reprint or License this content?


Web Database Applications with PHP and MySQL
Web Database Applications with PHP and MySQL, Second Edition

By Hugh E. Williams, David Lane
Book Price: $44.95 USD
£31.95 GBP
PDF Price: $35.99

Cover | Table of Contents | Colophon


Table of Contents

Chapter 1: Database Applications and the Web
Most of the services we enjoy on the Web are provided by web database applications. Web-based email, online shopping, forums and bulletin boards, corporate web sites, and sports and news portals are all database-driven. To build a modern web site, you need to develop a database application.
This book presents a highly popular, easy, low-cost way to bring together the Web and databases to build applications. The most popular database management system used in these solutions is MySQL, a very fast and easy-to-use system distributed under an Open Source license by its manufacturer, MySQL AB. We discuss MySQL in detail in this book.
With a web server such as Apache (we assume Apache in this book, although the software discussed here works with other web servers as well) and MySQL, you have most of what you need to develop a web database application. The key glue you need is a way for the web server to talk to the database; in other words, a way to incorporate database operations into web pages. The most popular glue that accomplishes this task is PHP.
PHP is an open source project of the Apache Software Foundation and it's the most popular Apache web server add-on module, with around 53% of the Apache HTTP servers having PHP capabilities. PHP is particularly suited to web database applications because of its integration tools for the Web and database environments. In particular, the flexibility of embedding scripts in HTML pages permits easy integration of HTML presentation and code. The database tier integration support is also excellent, with more than 15 libraries available to interact with almost all popular database servers. In this book, we present a comprehensive view of PHP along with a number of powerful extensions provided by a repository known as PEAR.
Apache, MySQL, and PHP can run on a wide variety of operating systems. In this book, we show you how to use them on Linux, Mac OS X, and Microsoft Windows.
This is an introductory book, but it gives you the sophisticated knowledge you need to build applications properly. This includes critical tasks such as checking user input, handling errors robustly, and locking your database operations to avoid data corruption. Most importantly, we explain the principles behind good web database applications. You'll finish the book with not only the technical skills to create an application, but also an appreciation for the strategies that make an application secure, reliable, maintainable, and expandable.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The Web
When you browse the Web, you use your web browser to request resources from a web server and the web server responds with the resources. You make these requests by filling in and submitting forms, clicking on links, or typing URLs into your browser. Often, resources are static HTML pages that are displayed in the browser. Figure 1-1 shows how a web browser communicates with a web server to retrieve this book's home page. This is the classic two-tier or client-server architecture used on the Web.
Figure 1-1: A two-tier architecture where a web browser makes a request and the web server responds
A web server is not sophisticated storage software. Complicated operations on data, done by commercial sites and anyone else presenting lots of dynamic data, should be handled by a separate database. This leads to a more complex architecture with three-tiers: the browser is still the client tier, the web server becomes the middle tier, and the database is the third or database tier. Figure 1-2 shows how a web browser requests a resource that's generated from a database, and how the database and web server respond to the request.
Figure 1-2: A three-tier architecture where a web browser requests a resource, and a response is generated from a database
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Three-Tier Architectures
This book shows you how to develop web database applications that are built around the three-tier architecture model shown in Figure 1-3. At the base of an application is the database tier, consisting of the database management system that manages the data users create, delete, modify, and query. Built on top of the database tier is the middle tier , which contains most of the application logic that you develop. It also communicates data between the other tiers. On top is the client tier , usually web browser software that interacts with the application.
Figure 1-3: The three-tier architecture model of a web database application
The three-tier architecture is conceptual. In practice, there are different implementations of web database applications that fit this architecture. The most common implementation has the web server (which includes the scripting engine that processes the scripts and carries out the actions they specify) and the database management system installed on one machine: it's the simplest to manage and secure, and it's our focus in this book. With this implementation on modern hardware, your applications can probably handle tens of thousands of requests every hour.
For popular web sites, a common implementation is to install the web server and the database server on different machines, so that resources are dedicated to permit a more scalable and faster application. For very high-end applications, a cluster of computers can be used, where the database and web servers are replicated and the load distributed across many machines. Our focus is on simple implementations; replication and load distribution are beyond the scope of this book.
Describing web database applications as three-tier architectures makes them sound formally structured and organized. However, it hides the reality that the applications must bring together different protocols and software, and that the software needs to be installed, configured, and secured. The majority of the material in this book discusses the middle tier and the application logic that allows web browsers to work with databases.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 2: The PHP Scripting Language
This chapter is the first of three that focus on the PHP scripting language. This chapter describes the PHP language basics. Chapter 3 describes PHP's support for arrays, strings, and other data types, and Chapter 4 introduces object-oriented programming in PHP.
If you're familiar with any programming language, PHP should be easy to learn. If you have done no programming before, the pace of this chapter may be brisk but should still be manageable. PHP has a syntax similar to JavaScript, which many web designers have learned; both languages hark back to the classic C and Perl languages in syntax.
The topics covered in this chapter include:
  • PHP basics, including script structure, variables, supported types, constants, expressions, and type conversions
  • Condition and branch statements supported by PHP, including if, if...else, and the switch statements
  • Looping statements
  • User-defined functions
We conclude the chapter with a short example that puts many of the basic PHP concepts together.
The current version of PHP is PHP4 (Version 4.3.4). PHP5 is available for beta testing at the time of writing as Version 5.0.0b3. We discuss both versions in this chapter.
PHP is a recursive acronym that stands for PHP: Hypertext Preprocessor; this is in the naming style of GNU, which stands for GNU's Not Unix and which began this odd trend. The name isn't a particularly good description of what PHP is and what it's commonly used for. PHP is a scripting language that's usually embedded or combined with the HTML of a web page. When the page is requested, the web server executes the PHP script and substitutes in the result back into the page. PHP has many excellent libraries that provide fast, customized access to DBMSs and is an ideal tool for developing application logic in the middle tier of a three-tier application.
Example 2-1 shows the first PHP script in this book, the ubiquitous "Hello, world." It's actually mostly HTML; the PHP is embedded near the end.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Introducing PHP
The current version of PHP is PHP4 (Version 4.3.4). PHP5 is available for beta testing at the time of writing as Version 5.0.0b3. We discuss both versions in this chapter.
PHP is a recursive acronym that stands for PHP: Hypertext Preprocessor; this is in the naming style of GNU, which stands for GNU's Not Unix and which began this odd trend. The name isn't a particularly good description of what PHP is and what it's commonly used for. PHP is a scripting language that's usually embedded or combined with the HTML of a web page. When the page is requested, the web server executes the PHP script and substitutes in the result back into the page. PHP has many excellent libraries that provide fast, customized access to DBMSs and is an ideal tool for developing application logic in the middle tier of a three-tier application.
Example 2-1 shows the first PHP script in this book, the ubiquitous "Hello, world." It's actually mostly HTML; the PHP is embedded near the end.
Example 2-1. The ubiquitous Hello, world in PHP
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                      "http://www.w3.org/TR/html401/loose.dtd">
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
  <title>Hello, world</title>
</head>
<body bgcolor="#ffffff">
  <h1>
  <?php
    print "Hello, world";
  ?>
  </h1>
</body>
</html>
When requested by a web browser, the script is run on the web server and the resulting HTML document sent back to the browser and rendered as shown in Figure 2-1.
Figure 2-1: The output of Example 2-1 shown in the Netscape browser
Example 2-1 illustrates the basic features of a PHP script. It's a mixture of HTML—in this case it's mostly HTML—and PHP code. The PHP code in this example:
<?php
  print "Hello, world";
?>
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Conditions and Branches
Conditionals add control to scripts and permit choices. Different statements are executed depending on whether expressions are true or false. There are two branching statements in PHP: if, with the optional else clause, and switch, usually with two or more case clauses.
The if statement conditionally controls execution. The basic format of an if statement is to test whether a condition is true and, if so, to execute one or more statements.
The following if statement executes the print statement and outputs the string when the conditional expression, $var is greater than 5, is true:
if ($var > 5)
    print "The variable is greater than 5";
The expressions used in the examples in this section compare integers. They can be used to compare strings but usually not with the expected results. If strings need to be compared, use the PHP string library function strcmp( ). It's discussed in more detail in Chapter 3.
Multiple statements can be executed as a block by encapsulating the statements within braces. If the expression evaluates as true, the statements within the braces are executed. If the expression isn't true, none of the statements are executed. Consider an example in which three statements are executed if the condition is true:
if ($var > 5)
{
    print "The variable is greater than 5.";

    // So, now let's set it to 5
    $var = 5;
    print "In fact, now it is equal to 5.";
}
Without the braces, an if statement executes only the single, immediately following statement when the conditional expression evaluates to true.
The if statement can have an optional else clause to execute a statement or block of statements if the expression evaluates as false. Consider an example:
if ($var > 5)
    print "Variable greater than 5";
else
    print "Variable less than or equal to 5";
It's also common for the
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Loops
Loops add control to scripts so that statements can be repeatedly executed as long as a conditional expression remains true. There are four loop statements in PHP: while, do...while, for, and foreach. The first three are general-purpose loop constructs, while the foreach is used exclusively with arrays and is discussed in the next chapter.
The while loop is the simplest looping structure but sometimes the least compact to use. The while loop repeats one or more statements—the loop body—as long as a condition remains true. The condition is checked first, then the loop body is executed. So, the loop never executes if the condition isn't initially true. Just as with the if statement, more than one statement can be placed in braces to form the loop body.
The following fragment illustrates the while statement by printing out the integers from 1 to 10 separated by a space character:
$counter = 1;
while ($counter < 11)
{
    print $counter . " ";
    $counter++;
}
The difference between while and do...while is the point at which the condition is checked. In do...while, the condition is checked after the loop body is executed. As long as the condition remains true, the loop body is repeated.
You can emulate the functionality of the previous while example as follows:
$counter = 1;
do
{
    print $counter . " ";
    $counter++;
} while ($counter < 11);
The contrast between while and do...while can be seen in the following example:
$counter = 100;
do
{
    print $counter . " ";
    $counter++;
} while ($counter < 11);
This example outputs 100, because the body of the loop is executed once before the condition is evaluated as false.
The do...while loop is the least frequently used loop construct, probably because executing a loop body once when a condition is false is an unusual requirement.
The for loop is the most complicated of the loop constructs, but it also leads to the most compact code.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Functions
A function is another concept that programming derived from mathematics. Some programming functions are direct implementations of common mathematical functions, such as sines and other trigonometric functions. (Naturally, these are not used much in PHP.) But you are sure to use functions related to strings, dates, and other everyday objects in your code. PHP has a large number of useful functions built in, and you can define your own functions as we describe later in this chapter.
Functions are called in PHP scripts and can often be used as expressions. For instance, the following example uses the strtoupper( ) function to change a string to uppercase:
$var = "A string";

print strtoupper($var); // prints "A STRING"
A function is followed by parentheses, which can contain zero or more parameters. This function accepts just one parameter. It can be summarized as follows:
string strtoupper(string subject)
The previous statement is called a prototype and is very useful for introducing functions. Prototypes are used throughout PHP documentation, and the following chapters of this book, when a function is described. The first word indicates what is returned by the function: in this case, its output is a string. The name of the function follows, and then a list of parameters within parentheses. Each parameter is described by a type and a parameter name—strtoupper( ) is defined with a single string parameter named subject. Names allow us to distinguish multiple parameters when we describe the function.
Prototypes use brackets to indicate that function parameters that are optional. Consider the following prototype for the date( ) function:
string date(string format [, integer timestamp])
The date( ) function returns the current date and time as a string where the format is specified by the parameter format. The optional integer parameter timestamp allows non-current dates and times to be formatted. We discuss the
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Working with Types
PHP is a loosely typed language, allowing variables and function parameters to be set to any type of data. Similarly, functions can return different data types in different circumstances.
In the last section, we introduced the function prototype as a way of describing the type of parameters that functions are designed to work with and the types of data that are returned. Since PHP is loosely typed, PHP can't enforce these types as strongly typed languages do. To illustrate this, the PHP library function strtoupper( ) is designed to operate on strings, but can be called with an integer parameter:
$var = 42;

print strtoupper($var); // prints the string "42"
When functions are designed to work with different data types, prototypes describe parameters and return values as mixed. Other functions may not work as expected, or may not work at all, when the wrong type of data is used.
PHP provides several mechanisms to allow variables of one type to be considered as another type. Variables can be explicitly converted to another type with the following functions:
string strval(mixed variable)
integer intval(mixed variable [, integer base])
float floatval(mixed variable)
The functions convert the variable into a string, integer, or float respectively. The intval( ) function also allows an optional base that determines how the variable is interpreted.
$year = 2003;

// Sets $yearString to the string value "2003"
$yearString = strval($year);

$var = "abc";

// sets $value to the integer 0
$value = intval($var);

// sets $count to the integer value 2748 - the 
// integer value of "abc" as a hexadecimal number
$count = intval($var, 16);
Because the string "abc" doesn't look anything like an integer, the first call to the
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
User-Defined Functions
User-defined functions provide a way to group together related statements into a cohesive block. For reusable code, a function saves duplicating statements and makes maintenance of the code easier. Consider an example of a simple user-developed function as shown in Example 2-3.
Example 2-3. A user-defined function to output bold text
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                      "http://www.w3.org/TR/html401/loose.dtd">
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
  <title>Simple Function Call</title>
</head>
<body bgcolor="#ffffff">
<?php

function bold($string)
{
    print "<b>" . $string . "</b>";
}

// First example function call (with a static string)
print "this is not bold ";
bold("this is bold ");
print "this is again not bold ";

// Second example function call (with a variable)
$myString = "this is bold";
bold($myString);
?>
</body></html>
The script defines the function bold( ), which takes one parameter, $string, and prints that string prefixed by a bold <b> tag and suffixed with a </b> tag. The parameter $string is a variable that is available in the body of the function, and the value of $string is set when the function is called. As shown in the example, the function can be called with a string literal expression or a variable as the parameter.
Functions can also return values. For example, consider the following code fragment that declares and uses a function heading( ), which returns a string using the return statement:
function heading($text, $headingLevel)
{
    switch ($headingLevel)
    {
    case 1:
        $result = "<h1>$text</h1>";
        break;

    case 2:
        $result = "<h2>$text</h2>";
        break;

    case 3:
        $result = "<h3>$text</h3>";
        break;

    default:
        $result = "<p><b>$text</b></p>";
    }
    return($result);
}

$test = "User-defined Functions";
print heading($test, 2);
The function takes two parameters: the text of a heading and a heading level. Based on the value of
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
A Working Example
In this section, we use some of the techniques described so far to develop a simple, complete PHP script. The script doesn't process input from the user, so we leave some of the best features of PHP as a web scripting language for discussion in later chapters.
Our example is a script that produces a web page containing the times tables. Our aim is to output the 1-12 times tables. The first table is shown in Figure 2-2 as rendered by a Mozilla browser.
Figure 2-2: The output of the times-tables script rendered in a Mozilla browser
The completed PHP script and HTML to produce the times tables are shown in Example 2-4. The first ten lines are the HTML markup that produces the <head> components and the <h1>The Times Tables</h1> heading at the top of the web page. Similarly, the last two lines are HTML that finishes the document: </body> and </html>.
Between the two HTML fragments that start and end the document is a PHP script to produce the times-table content and its associated HTML. The script begins with the PHP open tag <?php and finishes with the close tag ?>.
Example 2-4. A script to produce the times tables
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                      "http://www.w3.org/TR/html401/loose.dtd">
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
  <title>The Times-Tables</title>
</head>
<body bgcolor="#ffffff">
<h1>The Times Tables</h1>
<?php

// Go through each table
for($table=1; $table<13; $table++) 
{  
    print "<p><b>The " . $table . " Times Table</b>\n";

    // Produce 12 lines for each table
    for($counter=1; $counter<13; $counter++)
    {
        $answer = $table * $counter;

        // Is this an even-number counter?
        if ($counter % 2 == 0)
            // Yes, so print this line in bold
            print "<br><b>$counter x $table = " . 
                 "$answer</b>";

        else
            // No, so print this in normal face
            print "<br>$counter x $table = $answer";
    }
}

?>
</body>
</html>
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 3: Arrays, Strings, and Advanced Data Manipulation in PHP
In the previous chapter, we introduced the basics of the PHP language. In this chapter we show you some important techniques you'll need to manipulate data in PHP. This includes ways of dealing with arrays, strings, dates, and numerical data. The topics in this chapter cover:
  • Arrays and array library functions
  • Strings and string library functions
  • Regular expressions
  • Date and time functions
  • Integer and float functions
We don't attempt to cover every function and library supported by PHP. However, we provide brief descriptions of them in Appendix E. In later chapters, we discuss selected specialized library functions that support the topics and techniques presented here.
Programmers continually have to deal with collections of data items. For instance, when you query a database for products, you may get a collection with multiple results. In PHP, as with many programming languages, you can handle these results through an array. An array can be considered a name that refers to many related items.
Arrays in PHP are sophisticated and more flexible than in many other high-level languages. A PHP array is an ordered set of variables, in which each variable—called an element— has an associated key . PHP allows elements to be accessed using either string or integer keys—PHP automatically assigns integer key values if keys are not specified when arrays are constructed.
Arrays can hold scalar values (integers, Booleans, strings, or floats) or compound values (objects and even other arrays). The same array can even hold elements of different types. In this section, we show how arrays are constructed and introduce several useful array functions from the PHP library.
PHP provides the array( ) language construct that creates arrays. The following examples show how arrays of integers and strings can be constructed and assigned to variables for later use:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Arrays
Programmers continually have to deal with collections of data items. For instance, when you query a database for products, you may get a collection with multiple results. In PHP, as with many programming languages, you can handle these results through an array. An array can be considered a name that refers to many related items.
Arrays in PHP are sophisticated and more flexible than in many other high-level languages. A PHP array is an ordered set of variables, in which each variable—called an element— has an associated key . PHP allows elements to be accessed using either string or integer keys—PHP automatically assigns integer key values if keys are not specified when arrays are constructed.
Arrays can hold scalar values (integers, Booleans, strings, or floats) or compound values (objects and even other arrays). The same array can even hold elements of different types. In this section, we show how arrays are constructed and introduce several useful array functions from the PHP library.
PHP provides the array( ) language construct that creates arrays. The following examples show how arrays of integers and strings can be constructed and assigned to variables for later use:
$numbers = array(5, 4, 3, 2, 1);
$words = array("Web", "Database", "Applications");

// Print the third element from the array of integers: 3
print $numbers[2];

// Print the first element from the array of strings: "Web"
print $words[0];
By creating arrays this way, PHP assigns integer keys, or indexes to each element. By default, the index for the first element in an array is 0—this may seem odd but think of the index as an offset from the starting position in an array. The values contained in an array can be retrieved and modified using the bracket [ ] syntax. You can also create an array by assigning elements to a new, unset variable. The following code fragment illustrates the bracket syntax with an array of strings:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Strings
A string of characters is probably the most commonly used data type when developing scripts, and PHP provides a large library of string functions to help transform, manipulate, and otherwise manage strings. We introduced the basics of PHP strings in Chapter 2. In this section, we show you many of the useful PHP string functions.
The length property of a string is determined with the strlen( ) function, which returns the number of eight-bit characters in the subject string:
integer strlen(string subject)
We used strlen( ) earlier in the chapter to compare string lengths. Consider another simple example that prints the length of a 16-character string:
print strlen("This is a String");  // prints 16
In the previous chapter, we presented the basic method for outputting text with echo and print. Earlier in this chapter, we showed you the functions print_r( ) and var_dump( ), which can determine the contents of variables during debugging. PHP provides several other functions that allow more complex and controlled formatting of strings, and we discuss them in this section.

Section 3.2.2.1: Creating formatted output with sprintf( ) and printf( )

Sometimes, more complex output is required than can be produced with echo or print. For example, a floating-point value such as 3.14159 might need to be truncated to 3.14 in the output. For complex formatting, the sprintf( ) or printf( ) functions are useful:
string sprintf (string format [, mixed args...])
integer printf (string format [, mixed args...])
The operation of these functions is modeled on the identical C programming language functions, and both expect a
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Regular Expressions
In this section, we show how regular expressions can achieve more sophisticated pattern matching to find, extract, and replace complex substrings within a string. While regular expressions provide capabilities beyond those described in the last section, complex pattern matching isn't as efficient as simple string comparisons. The functions described in the previous section are more efficient than those that use regular expressions and should be used if complex pattern searches aren't required.
This section begins with a brief description of the POSIX regular expression syntax. This isn't a complete description of all of the capabilities, but we do provide enough details to create quite powerful regular expressions. The second half of the section describes the functions that use POSIX regular expressions. Examples of regular expressions can also be found in Chapter 9.
A regular expression follows a strict syntax to describe patterns of characters. PHP has two sets of functions that use regular expressions: one set supports the Perl Compatible Regular Expression (PCRE) syntax, and the other supports the POSIX extended regular expression syntax. In this book, we use the POSIX functions.
To demonstrate the syntax of regular expressions, we introduce the function ereg( ) :
boolean ereg(string pattern, string subject [, array var])
ereg( ) returns true if the regular expression pattern is found in the subject string. We discuss how the ereg( ) function can extract values into the optional array variable var later in this section.
The following trivial example shows how ereg( ) is called to find the literal pattern cat in the subject string "raining cats and dogs":
// prints "Found 'cat'"
if (ereg("cat", "raining cats and dogs"))
    print "Found 'cat'";
The regular expression cat matches the subject string, and the fragment prints "
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Dates and Times
There are several PHP library functions that work with dates and times. Most either generate a Unix timestamp or format a Unix timestamp in a human-readable form. Validation using dates, and working with the flexible PEAR Date package, is discussed in Chapter 9. In this section, we introduce timestamps and PHP library functions that work with Dates and Times.
A Unix timestamp consists of the number of seconds since the arbitrarily chosen time 1 January 1970 00:00:00 Greenwich Mean Time. Most systems represent a timestamp using a signed 32-bit integer, allowing a range of dates from December 13, 1901 through January 19, 2038. While timestamps are convenient to work with, care must be taken when manipulating timestamps to avoid integer overflow errors. While PHP automatically converts integers that overflow to floats, these values aren't valid timestamps.
In the Microsoft Windows environment, the timestamp functions don't support negative timestamps and can be used only with dates between January 1, 1970 and January 19, 2038.

Section 3.4.1.1: Current time

PHP provides several functions that generate a Unix timestamp. The simplest:
integer time( )
returns the timestamp for the current date and time, as shown in this fragment:
// prints the current timestamp: e.g., 1064699133
print time( );

Section 3.4.1.2: Creating timestamps with mktime( ) and gmmktime( )

To create a timestamp for a past or future date in the range December 13, 1901 through January 19, 2038, the mktime( ) and gmmktime( ) functions are defined:
int mktime(int hour, int minute, int second, int month, int day, int year [, int is_dst])
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Integers and Floats
As we discussed in Chapter 2, PHP supports both integer and floating-point numbers. PHP stores integers as a 32-bit signed word, providing a range of integers from -2147483647 to +2147483647. PHP automatically converts numbers that overflow out of this range to floats. You can see this behavior by adding one to the largest integer value:
// Largest positive integer (for a 32 bit signed integer)
$variable =  2147483647;

// prints int(2147483647)
var_dump($variable);

$variable++;

// prints float(2147483648)
var_dump($variable);
Floating-point numbers can store a wide range of values, both very large and very small, by storing a mantissa and an exponent. However a floating-point number can't precisely represent all numbers—for example, the fraction 2/3—and some precision can be lost.
Integers can be represented in a decimal, hexadecimal, or octal notation:
$var = 42;        // a positive integer
$var = -186;      // a negative integer
$var = 0654;      // 428 expressed as an octal number
$var = 0xf7;      // 247 expressed as a hexadecimal number
Floating-point numbers can represented in a decimal or exponential notation:
$var = 42.0;      // a positive float
$var = -186.123;  // a negative float
$var = 1.2e65;    // a very big number
$var = 10e-75;    // a very small number
Apart from the basic operators +, -, /, *, and %, PHP provides the usual array of mathematical library functions. In this section, we present some of the library functions that are used with integer and float numbers.
The absolute value of an integer or a float can be found with the abs( ) function:
integer abs(integer number)
float abs(float number)
The following examples show the result of abs( ) on integers and floats:
print abs(-1);       // prints 1
print abs(1);        // prints 1
print abs(-145.89);  // prints 145.89
print abs(145.89);   // prints 145.89
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 4: Introduction to Object-Oriented Programming with PHP 5
Object-oriented programming is a several-decades-old concept that has spread to almost every aspect of modern programming languages and practices. The reason is clear as soon as you start to use a convenience such as the powerful PHP-related packages. We introduce PEAR packages in Chapter 7; many operate by defining objects, providing a wealth of useful features in a simple form. You should understand the basics of object-oriented programming in order to make use of packages and an error-recovery feature called exceptions. You may also find object-oriented programming a useful practice in your own code. We'll give you an introduction in this chapter, and present some advanced features in Chapter 14.
While many of the concepts and techniques presented in this chapter work in PHP 4, support is greatly enhanced in PHP 5. In this chapter we describe what you can and can't do in each version of PHP.
The basic idea of object-oriented programming is to bind data and functions in convenient containers called objects . For instance, in Chapter 7 we'll show you how to standardize the look of your own web pages through an object called a template. Your PHP code can refer to this object through a variable; we'll assume here you've decided to call the variable $template. All the complex implementation of templates is hidden: you just load in the proper package and issue a PHP statement such as:
$template = new HTML_Template_IT("./templates");
As the statement suggests, you've just created a new object. The object is called $template and is built by the HTML_Template_IT package—a package whose code you don't need to know anything about. Once you have a template object, you can access the functionality provided by the HTML_Template_IT package.
After various manipulations of the $template object, you can insert the results into your web page through the PHP statement:
$template->show( );
The syntax of this statement is worth examining. As the parentheses indicate,
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Classes and Objects
The basic idea of object-oriented programming is to bind data and functions in convenient containers called objects . For instance, in Chapter 7 we'll show you how to standardize the look of your own web pages through an object called a template. Your PHP code can refer to this object through a variable; we'll assume here you've decided to call the variable $template. All the complex implementation of templates is hidden: you just load in the proper package and issue a PHP statement such as:
$template = new HTML_Template_IT("./templates");
As the statement suggests, you've just created a new object. The object is called $template and is built by the HTML_Template_IT package—a package whose code you don't need to know anything about. Once you have a template object, you can access the functionality provided by the HTML_Template_IT package.
After various manipulations of the $template object, you can insert the results into your web page through the PHP statement:
$template->show( );
The syntax of this statement is worth examining. As the parentheses indicate, show( ) is a function. However the -> operator associates show( ) with the object variable $template. When the function show( ) is called, it uses the data that is held by the $template object to calculate a result: put another way, show( ) is called on the $template object.
The functions that you can call depend on the support provided by the package—the show( ) function is provided by the HTML_Template_IT package and can be called on HTML_Template_IT objects such as $template. In traditional object-oriented parlance, show( ) is called a method or member function of the HTML_Template_IT object.
HTML_Template_IT is called a class because you can use it to create many similar template objects. Each time you issue a new statement you are said to create an instance of the class. Thus, the $template object is an instance of the
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Inheritance
Inheritance is available in PHP4 and PHP5.
One of the powerful concepts in object-oriented programming is inheritance. Inheritance allows a new class to be defined by extending the capabilities of an existing base class or parent class. PHP allows a new class to be created by extending an existing class with the extends keyword.
Example 4-7 shows how the UnitCounter class from Example 4-4 is extended to create the new class CaseCounter. The aim of the extended class is to track the number of cases or boxes that are needed to hold the units accumulated by the counter. For example, if bottles of wines are the units, then a case might hold 12 bottles.
Example 4-7. Defining the CaseCounter class by extending UnitCounter
<?php

// Access to the UnitCounter class definition
require "example.4-1.php";

class CaseCounter extends UnitCounter
{
    var $unitsPerCase;

    function addCase( )
    {
        $this->add($this->unitsPerCase);
    }

    function caseCount( )
    {
        return ceil($this->units/$this->unitsPerCase);
    }

    function CaseCounter($caseCapacity)
    {
        $this->unitsPerCase = $caseCapacity;
    }
}

?>
Before we discuss the implementation of the CaseCounter, we should examine the relationship with the UnitCounter class. Figure 4-1 illustrates this relationship in a simple class diagram . There are several different notations for representing class diagrams; we show the inheritance relationship by joining two classes with an annotated line with a solid arrowhead.
Figure 4-1: Class diagram showing UnitCounter and CaseCounter
The new CaseCounter class provides features related to counting cases worth of units—for example, bottles of wine—while the UnitCounter base class provides the counting and total weight capabilities. To create a CaseCounter object, the number of units that are stored in a case needs to be specified. This value is passed to the constructor when new
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Throwing and Catching Exceptions
PHP 5 has introduced an exception model that allows objects to be thrown and caught using the throw and try...catch statements.
The throw and try...catch statements provide a way of jumping to error handling code in exceptional circumstances: rather than terminating a script with a fatal error, exceptions are thrown, and can be caught and processed. The throw statement is always used in conjunction with the try...catch statement, and the following fragment shows the basic structure:
$total = 100;
$n = 5;

$result;

try
{
    // Check the value of $n before we use it
    if ($n == 0)
        throw new Exception("Can't set n to zero.");

    // Calculate an average
    $result = $total / $n;
}
catch (Exception $x)
{
    print "There was an error: {$x->getMessage( )};
}
The block of statements contained in the braces that follow the try keyword are executed normally as part of the script; the braces are required, even for a single statement. If a throw statement is called in the try block, then the statements contained in the braces that follow the catch keyword are executed. The throw statement throws an object and the catch block of code catches the thrown object, assigning it to the variable specified.
The catch statement specifies the type of object that is caught by placing the class name before the variable: the following fragment catches Exception objects and assigns them to the variable $x:
catch (Exception $x)
{
    print "There was an error: {$x->getMessage( )};
}
Specifying the type of object that is caught in the catch block is an example of a class type hint . We discuss class type hints in Chapter 14.
While objects of any class can be thrown, PHP5 predefines the Exception class that has useful features suitable for exception reporting.
Exception objects are constructed with a message and an optional integer error code. The message and error code are retrieved using the
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 5: SQL and MySQL
In this chapter, we introduce the SQL database query language and the MySQL© database management system. Using our case study winestore database as a worked example, we show you how to use SQL to define, manipulate, and query databases. At the end of this chapter, you'll have the database skills to build a database tier for your web database applications.
In this chapter, we cover the following topics:
  • A short introduction to relational databases
  • A quick start guide to the example winestore database and its entity-relationship model
  • The MySQL command interpreter and the basic features of MySQL
  • Using SQL to create and drop databases and tables
  • Using SQL to insert, delete, and update data
  • Querying with SQL, illustrated through examples and a case study
We assume that you have already installed MySQL and loaded the sample winestore database. If not, the guides in Appendix A through Appendix C will help you.
The techniques that we discuss are used to interact with MySQL after a database has been designed and expressed as SQL statements. An introduction to relational modeling and design can be found in Appendix E. Managing and using the MySQL database server, and more advanced SQL features, are discussed in Chapter 15. Chapter 8 covers issues that arise when multiple users are writing to web databases.
The field of databases has its own terminology. Terms such as database, table, attribute, row, primary key, and relational model have specific meanings and are used throughout this chapter. In this section, we present an example of a simple database to introduce the basic components of relational databases, and we list and define selected terms used in the chapter. We then show you our winestore database that we use throughout our examples in this chapter, and as the basis of our sample application in Chapter 16 through Chapter 20. More detail on the database can be found in Appendix E.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Database Basics
The field of databases has its own terminology. Terms such as database, table, attribute, row, primary key, and relational model have specific meanings and are used throughout this chapter. In this section, we present an example of a simple database to introduce the basic components of relational databases, and we list and define selected terms used in the chapter. We then show you our winestore database that we use throughout our examples in this chapter, and as the basis of our sample application in Chapter 16 through Chapter 20. More detail on the database can be found in Appendix E.
A simple example relational database is shown in Figure 5-1. This database stores data about wineries and the wine regions they are located in. A relational database is organized into tables, and there are two tables in this example: a winery table that stores in