Tuesday, August 11, 2009

General PHP

rograms are the application part of your Web database application. Programs perform the tasks. They create and display Web pages, accept
and process information from users, store information in the database, get information out of the database, and perform any other necessary tasks.

PHP, the language that you use to write your programs, is a scripting lan­ guage designed specifically for use on the Web. It is your tool for creating dynamic Web pages. It has features designed to aid you in programming the tasks needed by dynamic Web applications.

In this chapter, I describe the general rules for writing PHP programs — the rules that apply to all PHP statements. Consider these rules similar to general grammar and punctuation rules. In the remaining chapters in Part III, you find out about specific PHP statements and features and how to write PHP pro­ grams to perform specific tasks.

Adding a PHP Section to an HTML Page

PHP is a partner to HTML (HyperText Markup Language) that extends its abil­ ities. It enables an HTML program to do things it can’t do on its own. For example, HTML programs can display Web pages, and HTML has features
that allow you to format those Web pages. HTML also allows you to display graphics in your Web pages and to play music files. But HTML alone does not allow you to interact with the person viewing the Web page.

How the Web server processes PHP files

When a browser is pointed to a regular HTML file with an .html or .htm extension, the Web server sends the file, as-is, to the browser. The browser processes the file and displays the Web page that is described by the HTML tags in the file. When a browser is pointed to a PHP file (with a .php extension), the Web server looks for PHP sections in the file and processes them instead of just sending them as-is to the browser. The steps that the Web server uses to process a PHP file are as follows:

1. The Web server starts scanning the file in HTML mode. It assumes that the statements are HTML and sends them to the browser without any processing.

2. The Web server continues in HTML mode until it encounters a PHP opening tag (<?php).

3. When it encounters a PHP opening tag, the Web server switches into PHP mode. This is sometimes called escaping from HTML. The Web server then assumes that all state­ ments are PHP statements and executes the PHP statements. If there is output, the output is sent by the server to the browser.

4. The Web server continues in PHP mode until it encounters a PHP closing tag (?>).

5. When the Web server encounters a PHP closing tag, it returns to HTML mode. It resumes scanning, and the cycle continues from Step 1.

HTML is almost interactive. That is, HTML forms allow users to type informa­ tion that the Web page is designed to collect; however, you can’t access that information without using a language other than HTML. PHP processes form information, without requiring a separate program, and allows other interac­ tive tasks as well.

HTML tags are used to make PHP language statements part of HTML programs. The program file is named with a .php extension. Other extension(s) can be defined by the PHP administrator, such as .phtml, .php4, or .php5, but .php
is the most common. So for this book, I will assume that .php is the extension for PHP programs. The PHP language statements are enclosed in PHP tags with the following form:

<?php ?>

Sometimes you can use a shorter version of the PHP tags. You can try using
<? and ?> without the php. If short tags are enabled, you can save a little typing.

PHP processes all statements between the two PHP tags. After the PHP sec­ tion is processed, it’s discarded. Or, if the PHP statements produce output, the PHP section is replaced by the output. The browser does not see the PHP section — only its output if there is any output. For more on this process, check out the sidebar, “How the Web server processes PHP files.”

As an example, I’ll start with a program that displays Hello World! in the browser window. (It’s sort of a tradition that the first program you write in any language is the Hello World program. You might have written a Hello World program when you first learned HTML.) Listing 6-1 shows an HTML program that displays Hello World! in a browser window.

Listing 6-1: The Hello World HTML Program

<html>
<head><title>Hello World Program</title></head>
<body>
<p>Hello World!
</body>
</html>

If you point your browser at this HTML program, you see a Web page that displays

Hello World!

in the browser window.

Listing 6-2 shows a PHP program that does exactly the same thing — it dis­
plays Hello World! in a browser window.

Listing 6-2: The Hello World PHP Program

<html>
<head><title>Hello World Program</title></head>
<body>
<?php
echo “<p>Hello World!”
?>
</body>
</html>

If you point your browser at this program, it displays exactly the same Web page as the HTML program in Listing 6-1.

Don’t look at the file directly with your browser. That is, don’t choose File➪Open➪Browse from your browser menu to navigate to the file and click it. You must point at the file by typing its URL, as I discuss in Chapter 2. If you see the PHP code displayed in the browser window instead of the output that you expect, you might not have pointed to the file by using its URL.

In this PHP program, the PHP section is

<?php
echo “<p>Hello World!”
?>

The PHP tags enclose only one statement — an echo statement. The echo statement is a PHP statement that you will use frequently. It simply outputs the text between the double quotes.

There is no rule that says you must enter the PHP on separate lines. You could just as well include the PHP in the file on a single line, like this:

<?php echo “<p>Hello World!” ?>

When the PHP section is processed, it is replaced with the output. In this case, the output is

<p>Hello World!

If you replace the PHP section in Listing 6-2 with the preceding output, the program now looks exactly like the HTML program in Listing 6-1. If you point your browser at either program, you see the same Web page. If you look at the source code that the browser sees (in the browser, choose View➪Source), you see the same source code listing for both programs.

Writing PHP Statements

The PHP section that you add to your HTML file consists of a series of PHP statements. Each PHP statement is an instruction to PHP to do something. In the Hello World program shown in Listing 6-2, the PHP section contains only one simple PHP statement. The echo statement instructs PHP to output the text between the double quotes.

PHP statements end with a semicolon (;). PHP does not notice white space or the end of lines. It continues reading a statement until it encounters a semicolon or the PHP closing tag, no matter how many lines the statement spans. Leaving out the semicolon is a common error, resulting in an error message that looks something like this:

Parse error: expecting `’,’’ or `’;’’ in /hello.php on line 6

Notice that the error message gives you the line number where it encoun­ tered problems. This information helps you locate the error in your program. This error message probably means that the semicolon was omitted at the end of line 5.

I recommend writing your PHP programs with an editor that uses line num­ bers. If your editor doesn’t let you specify which line you want to go to, you have to count the lines manually from the top of the file every time that you receive an error message. Many editors that are good for editing PHP are listed at phpeditors.linuxbackup.co.uk.

Sometimes groups of statements are combined together into a block. A block is enclosed by curly braces ( { } ). A block of statements execute together. A common use of a block is in a conditional block, in which statements are exe­ cuted only when certain conditions are true. For instance, you might want your program to do the following:

if (the sky is blue)
{
put leash on dragon;
take dragon for a walk in the park;
}

These statements are enclosed in curly braces to ensure that they execute as a block. If the sky is blue, both put leash on dragon and take dragon
for a walk in the park are executed. If the sky is not blue, neither state­
ment is executed (no leash; no walk).

PHP statements that use blocks, such as if statements (which I explain in Chapter 7), are complex statements. PHP reads the entire complex statement, not stopping at the first semicolon that it encounters. PHP knows to expect one or more blocks and looks for the ending curly brace of the last block in complex statements. Notice that there is a semicolon before the ending brace. This semicolon is required, but no semicolon is required after the ending curly brace.

If you wanted to, you could write the entire PHP section in one long line, as long as you separated statements with semicolons and enclosed blocks with curly braces. However, a program written this way would be impossible for people to read. Therefore, you should put statements on separate lines, except for occasional, really short statements.

Notice that the statements inside the block are indented. Indenting is not nec­ essary for PHP. Indenting is strictly for readability. You should indent the statements in a block so that people reading the script can tell more easily where a block begins and ends.

In general, PHP doesn’t care whether the statement keywords are in upper- or lowercase. Echo, echo, ECHO, and eCHo are all the same to PHP.

Error messages and warnings

PHP tries to be helpful when problems arise. It provides error messages and warnings as follows:

Error message: You receive this message when the program has a problem that pre­ vents it from running. The message con­ tains as much information as possible to help you identify the problem. A common error message is

Parse error: parse error in c:\catalog\test.php on line 6

Often, you receive this error message because you’ve forgotten a semicolon, a parenthesis, or a curly brace.

Warning message: You receive this mes­ sage when the program sees a problem but the problem is not serious enough to pre­ vent the program from running. Warning messages do not mean that the program can’t run; the program does continue to run. Rather, warning messages tell you that PHP believes that something is probably wrong. You should identify the source of the warn­ ing and then decide whether it needs to be fixed. It usually does.

Notice: You receive a notice when PHP sees a condition that might be an error or might be perfectly okay. Notices, like warn­ ings, do not cause the script to stop running. Notices are much less likely to indicate serious problems than warnings. Notices just tell you that you are doing something unusual and to take a second look at what you’re doing to be sure that you really want to do it.

One common reason why you might receive a notice is if you’re echoing variables that don’t exist. Here’s an example of what you might see in that instance:

Notice: Undefined variable: age in testing.php on line 9

Notice that all types of messages indicate the filename causing the problem and the line number where the problem was encountered.

PHP has several kinds of error and warning mes­ sages. Which kinds are sent depends on the error message level that PHP is set to. You do want to see all the error messages, but you might not want to see all the warnings and notices. Often the only problem with a notice is the unsightly message; the code does exactly what you want it to do. Or, you might want notices dis­ played during development but not after the application is being used by customers.

To change the error message level for your Web site to show more or fewer messages, you must be the PHP administrator. Edit the php.ini file on your system. It contains a section that explains the error message levels and how to set them. Change the line that sets your error message level and then save the edited php.ini file. Note: You might need to restart your Web server before the changes in the PHP configuration file take effect.

If you are not the PHP administrator for your system and don’t have access to php.ini, you can add a statement to any program that sets the error reporting level for that program only. To set the error level, add the following state­ ment at the beginning of the program:

error_reporting(OPTIONS);

OPTIONS is a code that tells PHP what error reporting level to use. To see all errors, use the following:
error_reporting(E_ALL);

To see all errors except notices, use the following:
error_reporting(E_ALL &
~E_NOTICE);

OPTIONS can be any of the codes described in the php.ini file.

Using PHP Variables

Variables are containers used to hold information. A variable has a name, and information is stored in the variable. For instance, you might name a variable
$age and store the number 12 in it. After information is stored in a variable, it can be used later in the program. One of the most common uses for variables is to hold the information that a user types into a form.

Naming a variable

When you’re naming a variable, keep the following rules in mind:

All variable names have a dollar sign ($) in front of them. This tells PHP
that it is a variable name.

Variable names can be any length.

Variable names can include letters, numbers, and underscores only.

Variable names must begin with a letter or an underscore. They cannot begin with a number.

Uppercase and lowercase letters are not the same. For example,
$firstname and $Firstname are not the same variable. If you store information in $firstname, you can’t access that information by using the variable name $firstName.

When you name variables, use names that make it clear what information is in the variable. Using variable names like $var1, $var2, $A, or $B does not contribute to the clarity of the program. Although PHP doesn’t care what you name the variable and won’t get mixed up, people trying to follow the pro­ gram will have a hard time keeping track of which variable holds what infor­ mation. Variable names like $firstName, $age, and $orderTotal are much more descriptive and helpful.

Creating and assigning values to variables

Variables can hold either numbers or strings of characters. You store infor­ mation in variables by using a single equal sign (=). For instance, the follow­ ing four PHP statements assign information to variables:

$age = 12;
$price = 2.55;
$number=-2;
$name = “Goliath Smith”;

Notice that the character string is enclosed in quotes but the numbers are not. Details about using numbers and characters are described later in this chapter. (See “Working with Numbers” and “Working with Character Strings.”)

You can now use any of these variable names in an echo statement to see the value in that variable. For instance, if you use the following PHP statement in a PHP section:

echo $age;

the output is 12. If you include the following line in an HTML file:

<p>Your age is <?php echo $age ?>.

the output on the Web page is

Your age is 12.

Whenever you put information into a variable that did not exist before, you create that variable. For instance, suppose you use the following PHP statement:

$firstname = “George”;

If this statement is the first time that you’ve mentioned the variable
$firstname, this statement creates the variable and sets it to “George”. If you have a previous statement setting $firstname to “Mary”, this statement changes the value of $firstname to “George”.

You can also remove information from a variable. For example, the following statement takes information out of the variable $age:

$age = “”;

The variable $age exists but does not contain a value. It does not mean that
$age is set to 0 because zero is a value. It means that $age does not store any information at all.

You can go even further and uncreate the variable by using this statement:

unset($age);

After this statement is executed, the variable $age no longer exists.

A variable keeps its information for the whole program, not just for a single PHP section. If a variable is set to “yes” at the beginning of a file, it will still hold “yes” at the end of the page. For instance, suppose your file has the fol­ lowing statements:

<p>Hello World!
<?php
$age = 15;
$name = “Harry”;
?>
<br>Hello World again!<br>
<?php
echo $name;
?>

The echo statement in the second PHP section will display Harry. The Web page resulting from these statements is

Hello World!
Hello World again! Harry

Dealing with notices

If you use a statement that includes a variable that does not exist, you might get a notice. It depends on the error message level that PHP is set to. Remember that notices aren’t the same as error messages; notices don’t mean the program can’t run — the program does continues to run. Notices just tell you that you’re doing something unusual and to take a second look at what you’re doing to be sure that you really want to do it. (See the sidebar, “Error messages and warn­ ings.”) For instance, suppose you use the following statements:

unset($age);
echo $age;
$age2 = $age;

You might see two notices: one for the second statement and one for the third statement. The notices will look something like this:

Notice: Undefined variable: age in testing.php on line 9

Suppose that you definitely want to use these statements. The program works exactly the way you want it to. The only problems are the unsightly notices. You can prevent notices within a program by inserting an at sign (@) at the point where the notice would be issued. For instance, you can prevent the notices generated by the preceding statements if you change the state­ ments to this:

unset($age);
echo @$age;
$age2 = @$age;

If you are the PHP administrator, you can change the error message level so that notices are not displayed. For details on how to do this, check out the sidebar, “Error messages and warnings,” elsewhere in this chapter.

Using PHP Constants

PHP constants are very similar to variables. Constants are given a name, and a value is stored in them. However, constants are constant; that is, they can’t be changed by the program. After you set the value for a constant, it stays the same. If you used a constant for age and set it to 29, it can’t be changed. Wouldn’t that be nice — 29 forever?

Constants are used when information is used several places in the program and doesn’t change during the program. It’s useful to set a constant for the value at the beginning of the program and use it throughout the program. By making it a constant instead of a variable, you make sure that it won’t get changed accidentally. By giving it a name, you know what the information is instantly. And by setting a constant once at the start of the program (instead of using the value throughout the program), you can change the value in one place if it needs changing instead of hunting for it in many places in the pro­ gram to change it.

For instance, you might set a constant that’s the company name and a constant that’s the company address and use them wherever needed. Then, if the com­ pany moved, you could just change the value in the company address at the start of the program instead of having to find every place in your program that echoed the company name to change it.

Constants are set by using the define statement. The format is

define(“constantname”,”constantvalue”);

For instance, to set a constant with the company name, use the following statement:

define(“COMPANY”,”ABC Pet Store”);

Now use the constant in your program wherever you need your company name:

echo COMPANY;

When you echo a constant, you can’t enclose it in quotes. If you do, it will echo the constant name, instead of the value. You can echo it without any­ thing, as shown in the preceding example, or enclosed with parentheses.

You can use any name for a constant that you can use for a variable, but con­ stant names do not begin with a dollar sign ($). By convention, constants are given names that are all uppercase, so you can see easily that they’re con­ stants. However, PHP itself doesn’t care what you name a constant. You can store either a string or a number in it. The following statement is perfectly okay with PHP:

define (“AGE”,29);

Just don’t expect Mother Nature to believe it.

Working with Numbers

PHP allows you to do arithmetic operations on numbers. You indicate arith­ metic operations with two numbers and an arithmetic operator. For instance, one operator is the plus (+) sign, so you can indicate an arithmetic operation like this:

1 + 2

You can also perform arithmetic operations with variables that contain num­
bers, as follows:

$n1 = 1;
$n2 = 2;
$sum = $n1 + $n2;

Table 6-1 shows the arithmetic operators that you can use.

You can do several arithmetic operations at once. For instance, the following statement performs three operations:

$result = 1 + 2 * 4 + 1;

The order in which the arithmetic is performed is important. You can get dif­ ferent results depending on which operation is performed first. PHP does multiplication and division first, followed by addition and subtraction. If
other considerations are equal, PHP goes from left to right. Consequently, the preceding statement sets $result to 10, in the following order:

$result = 1 + 2 * 4 + 1 (first, it does the multiplication)
$result = 1 + 8 + 1 (next, it does the leftmost addition)
$result = 9 + 1 (next, it does the remaining addition)
$result = 10

You can change the order in which the arithmetic is performed by using parentheses. The arithmetic inside the parentheses is performed first. For instance, you can write the previous statement with parentheses like this:

$result = (1 + 2) * 4 + 1;

This statement sets $result to 13, in the following order:

$result = (1 + 2) * 4 + 1 (first, it does the math in the parentheses)
$result = 3 * 4 + 1 (next, it does the multiplication)
$result = 12 + 1 (next, it does the addition)
$result = 13

On the better-safe-than-sorry principle, it’s best to use parentheses whenever more than one answer is possible.

Often, the numbers that you work with are dollar amounts, such as product prices. You want your customers to see prices in the proper format on Web pages. In other words, dollar amounts should always have two decimal

places. However, PHP stores and displays numbers in the most efficient format. If the number is 10.00, it is displayed as 10. To put numbers into the proper format for dollars, you can use sprintf. The following statement for­ mats a number into a dollar amount:

$newvariablename = sprintf(“%01.2f”, $oldvariablename);

This statement reformats the number in $oldvariablename and stores it in the new format in $newvariablename. For example, the following statements display money in the correct format:

$price = 25;
$f_price = sprintf(“%01.2f”,$price);
echo “$f_price<br>”;

You see the following on the Web page:

25.00

sprintf can do more than format decimal places. For more information on using sprintf to format values, see Chapter 13.

If you want commas to separate thousands in your number, you can use number_format. The following statement creates a dollar format with commas:

$price = 25000;
$f_price = number_format($price,2);
echo “$f_price<br>”;

You see the following on the Web page:

25,000.00

The 2 in the number_format statement sets the format to two decimal places. You can use any number to get any number of decimal places.

Working with Character Strings

A character string is a series of characters. Characters are letters, numbers, and punctuation. When a number is used as a character, it is just a stored character, the same as a letter. It can’t be used in arithmetic. For instance, a phone number is stored as a character string because it only needs to be stored — not added or multiplied.

When you store a character string in a variable, you tell PHP where the string begins and ends by using double quotes or single quotes. For instance, the following two statements are the same.

$string = “Hello World!”;
$string = ‘Hello World!’;

Suppose that you wanted to store a string as follows:

$string = ‘It is Tom’s house’;
echo $string;

These statements won’t work because when PHP sees the ‘ (single quote)
after Tom, it thinks that this is the end of the string and displays the following:

It is Tom

You need to tell PHP to interpret the single quote (‘) as an apostrophe instead of the end of the string. You can do this by using a backslash (\) in front of the single quote. The backslash tells PHP that the single quote does not have any special meaning; it’s just an apostrophe. This is escaping the character. Use the following statements to display the entire string:

$string = ‘It is Tom\’s house’;
echo $string;

Similarly, when you enclose a string in double quotes, you must also use a backslash in front of any double quotes in the string.

Single-quoted strings versus double-quoted strings

Single-quoted and double-quoted strings are handled differently. Single- quoted strings are stored literally, with the exception of \’, which is stored as an apostrophe. In double-quoted strings, variables and some special char­ acters are evaluated before the string is stored. Here are the most important differences in the use of double or single quotes when writing programs:

Handling variables: If you enclose a variable in double quotes, PHP uses the value of the variable. However, if you enclose a variable in single quotes, PHP uses the literal variable name. For example, if you use the following statements:

$age = 12;
$result1 = “$age”;
$result2 = ‘$age’;
echo $result1; echo “<br>”; echo $result2;

the output is

12
$age

Starting a new line: The special characters \n tell PHP to start a new line. When you use double quotes, PHP starts a new line at \n, but with single quotes, \n is a literal string. For instance, when using the follow­ ing statements:

$string1 = “String in \ndouble quotes”;
$string2 = ‘String in \nsingle quotes’;

string1 outputs as

String in double quotes

and string2 outputs as

String in \nsingle quotes

Inserting a tab: The special characters \t tell PHP to insert a tab. When you use double quotes, PHP inserts a tab at \t, but with single quotes,
\t is a literal string. For instance, when using the following statements:

$string1 = “String in \tdouble quotes”;
$string2 = ‘String in \tsingle quotes’;

string1 outputs as

String in double quotes

and string2 outputs as

String in \tsingle quotes

The quotes that enclose the entire string determine the treatment of variables and special characters, even if there are other sets of quotes inside the string. For example, look at the following statements:

$number = 10;
$string1 = “There are ‘$number’ people in line.”;
$string2 = ‘There are “$number” people waiting.’;
echo $string1,”<br>\n”;
echo $string2;

The output is as follows:

There are ‘10’ people in line.
There are “$number” people waiting.

Joining strings

You can join strings, a process called concatenation, by using a dot (.). For instance, you can join strings with the following statements:

$string1 = ‘Hello’;
$string2 = ‘World!’;
$stringall = $string1.$string2;
echo $stringall;

The echo statement outputs

HelloWorld!

Notice that no space appears between Hello and World. That’s because no spaces are included in the two strings that are joined. You can add a space between the words by using the following concatenation statement rather than the earlier statement:

$stringall = $string1.” “.$string2;

You can use .= to add characters to an existing string. For example, you can use the following statements in place of the preceding statements:

$stringall = “Hello”;
$stringall .= “ World!”;
echo $stringall;

The echo statement outputs this:

Hello World!

You can also take strings apart. You can separate them at a given character or look for a substring in a string. You use functions to perform these and other operations on a string. I explain functions in Chapter 7.

Working with Dates and Times

Dates and times can be important elements in a Web database application. PHP has the ability to recognize dates and times and handle them differently than plain character strings. Dates and times are stored by the computer in a format called a timestamp. However, this is not a format in which you or I would want to see the date. PHP converts dates from your notation into a timestamp that the computer understands and from a timestamp into a format that is familiar to people. PHP handles dates and times by using built-in functions.

The timestamp format is a Unix Timestamp, which is an integer that is the number of seconds from January 1, 1970 00:00:00 GMT (Greenwich Mean Time) to the time represented by the timestamp. This format makes it easy to calcu­ late the time between two dates — just subtract one timestamp from the other.

Formatting a date

The function that you will use most often is date. date converts a date or time from the timestamp format into a format that you specify. The general format is

$mydate = date(“format”,$timestamp);

$timestamp is a variable with a timestamp stored in it. You previously stored the timestamp in the variable, using a PHP function as I describe later in this section. If $timestamp is not included, the current time is obtained from the operating system and used. Thus, you can get today’s date with the following statement:

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

If today is August 10, 2003, this statements returns

2003/08/10

The format is a string that specifies the date format that you want stored in the variable. For instance, the format “yy-m-d” returns 03-8-10, and “M.d.yyyy” returns Aug.10.2003. Table 6-2 lists some of the symbols that you can use in
the format string. (For a complete list of symbols, see the documentation at www.php.net.) The parts of the date can be separated by hyphens (-), dots (.), forward slashes (/), or spaces.

Storing a timestamp in a variable

You can assign a timestamp with the current date and time to a variable with the following statements:

$today = time();

Another way to store a current timestamp is with the statement

$today = strtotime(“today”);

You can store specific timestamps by using strtotime with various key­ words and abbreviations that are very much like English. For instance, you can create a timestamp for January 15, 2003, as follows:

$importantDate = strtotime(“January 15 2003”);

strtotime recognizes the following words and abbreviations:

Month names: Twelve month names and abbreviations

Days of the week: Seven days and some abbreviations

Time units: Year, month, fortnight, week, day, hour, minute, second,
am, pm

Some useful English words: ago, now, last, next, this, tomorrow, yesterday

Plus and minus: + or –

All numbers

Time zones: For example, gmt (Greenwich Mean Time), pdt (Pacific
Daylight Time), and akst (Alaska Standard Time)

You can combine the words and abbreviations in a wide variety of ways. The following statements are all valid:

$importantDate = strtotime(“tomorrow”); #24 hours from now
$importantDate = strtotime(“now + 24 hours”);
$importantDate = strtotime(“last saturday”);
$importantDate = strtotime(“8pm + 3 days”);
$importantDate = strtotime(“2 weeks ago”); # at current time
$importantDate = strtotime(“next year gmt”); #1 year from now
$importantDate = strtotime(“this 4am”); # 4 AM today

If you wanted to know how long ago $importantDate was, you could sub­
tract it from $today. For instance:

$timeSpan = $today - $importantDate;

This gives you the number of seconds between the important date and today. Or use the statement

$timeSpan =(($today - $importantDate)/60)/60

to find out the number of hours since the important date.

Using dates with MySQL

Often you want to store a date in your MySQL database. For instance, you might want to store the date when a customer made an order or the time when a member logged in. MySQL also recognizes dates and times and han­ dles them differently than plain character strings. However, MySQL handles them differently than PHP. In order to use dates and times in your applica­ tion, you need to understand both how PHP handles dates (which I describe in the previous few sections) and how MySQL handles dates.

I discuss the DATE and DATETIME data types for MySQL in detail in Chapter 3. The following is a summary.

DATE: MySQL date columns expect dates with the year first, the month second, and the day last. The year can be yyyy or yy. The month can be mm or m. The day can be dd or d. The parts of the date can be separated by a hyphen (-), a forward slash (/), a dot (.), or a space.

DATETIME: MySQL datetime columns expect both the date and the time.
The date is formatted as I describe in the preceding bullet. The date is followed by the time in the format hh:mm:ss.

Dates and times must be formatted in the correct MySQL format to store them in your database. PHP functions can be used for formatting. For instance, you can format today’s date into a MySQL format with this statement:

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

You can format a specific date by using the statement

$importantDate = date(“Y.m.d”,strtotime(“Jan 15 2003”));

You can then store the formatted date in a database with an SQL query like this:

UPDATE Member SET createDate=”$today”

Comparing Values

In programs, you often use conditional statements. That is, if something is
true, your program does one thing, but if something is not true, your program does something different. Here are two examples of conditional statements:

if user is a child show toy catalog
if user is not a child
show electronics catalog

In order to know which conditions exist, the program must ask questions. Your program then performs tasks based on the answers. Some questions (conditions) that you might want to ask — and the actions that you might want taken — are

Is the customer a child? If so, display a toy catalog.

Which product has more sales? Display the most popular one first.

Did the customer enter the correct password? If so, display the
Members Only Web page.

Does the customer live in Ohio? If so, display the map to the Ohio store location.

To ask a question in a program, you form a statement that compares values. The program tests the statement and determines whether the statement is true or false. For instance, you can state the preceding questions as

The customer is less than 13 years of age. True or false? If true, display the toy catalog.

Product 1 sales are higher than Product 2 sales. True or false? If true, display Product 1 first; if false, display Product 2 first.

The customer’s password is secret. True or false? If true, show the
Members Only Web page.

The customer lives in Ohio. True or false? If true, display a map to the
Ohio store location.

Comparisons can be quite simple. For instance, is the first value larger than the second value? Or smaller? Or equal to? But sometimes you need to look at character strings to see whether they have certain characteristics instead of looking at their exact values. For instance, you might want to identify strings that begin with S or strings that look like phone numbers. For this type of com­ parison, you compare a string to a pattern, which I describe in the section “Matching character strings to patterns,” later in this chapter.

Making simple comparisons

Simple comparisons compare one value to another value. PHP offers several ways to compare values. Table 6-3 shows the comparisons that are available

You can compare both numbers and strings. Strings are compared alphabeti­ cally, with all uppercase characters coming before any lowercase characters. For instance, SS comes before Sa. Characters that are punctuation also have an order, and one character can be found to be larger than another character. However, comparing a comma to a period doesn’t have much practical value.

Strings are compared based on their ASCII (American Standard Code for
Information Interchange) code. In the ASCII character set, each character
is assigned an ASCII code that corresponds to a decimal number between 0 and 127. When strings are compared, they are compared based on this code. For instance, the number that represents the comma is 44. The period corre­ sponds to 46. Therefore, if a period and a comma are compared, the period is seen as larger.

Comparisons are often used to execute statements only under certain condi­ tions. For instance, in the following example, the block of statements is only executed when the comparison $weather == “raining” is true:

if ( $weather == “raining” )
{
put up umbrella;
cancel picnic;
}

PHP checks the variable $weather to see whether it is equal to “raining”. If
it is, PHP executes the two statements. If $weather is not equal to “raining”, PHP does not execute the two statements.

The comparison sign is two equal signs (==). One of the most common mis­ takes is to use a single equal sign for a comparison. A single equal sign puts the value into the variable. Thus, a statement like if ($weather = “raining”) would set $weather to raining rather than check whether it already equaled raining and would thus always be true.

For example, here’s a solution to the programming problem presented at the beginning of this section. The problem is

if user is a child show toy catalog
if user is not a child
show electronics catalog

To determine whether a customer is an adult, you compare the customer’s age with the age when the customer is considered to be an adult. You need to decide at what age a customer would stop being interested in toy catalogs and start being more interested in electronic catalogs. Suppose you decide that 13 seems like the right age. You then ask whether the customer is younger than
13 by comparing the customer’s age to 13. If the age is less than 13, show the toy catalog; if the age is 13 or over, show the electronics catalog. These com­ parisons would have the following format:

$age < 13 (is the customer’s age less than 13?)
$age >= 13 (is the customer’s age greater than or equal to 13?)

One way to program the conditional actions is to use the following statements:

if ($age < 13)
$status = “child”;
if ($age >= 13)
$status = “adult”;

These statements instruct PHP to compare the customer’s age to 13. In the first statement, if the customer’s age is less than 13, the customer’s status is set to “child”. In the second statement, if the customer’s age is equal to 13 or greater than 13, the customer’s status is set to “adult”. You then show the toy catalog to customers whose status is child and show the electronic catalog to those whose status is adult. Although you can write these if statements in a more efficient way, the statements shown will work. A full description of conditional statements is provided in Chapter 7.

Matching character strings to patterns

Sometimes you need to compare character strings to see whether they fit certain characteristics rather than whether they match exact values. For instance, you might want to identify strings that begin with S or strings that have numbers in them. For this type of comparison, you compare the string to a pattern. These patterns are regular expressions.

You’ve probably used some form of pattern matching in the past. For instance, when you use an asterisk (*) as a wildcard when searching for files (dir s*.doc or ls s*.txt), you are pattern matching. For instance, c*.txt is a pattern. Any string that begins with a c and ends with the string .txt, with any characters in between the c and the .txt, matches the pattern. The strings cow.txt, c3333.txt, and c3c4.txt all match the pattern. Using reg­ ular expressions is just a more complicated variation of using wildcards.

The most common use for pattern matching on Web pages is to check the input from a form. If the information doesn’t make sense, it’s probably not something that you want to store in your database. For instance, if the user types a name into a form, you can check whether it seems like a real name by matching patterns. You know that a name consists mainly of letters and spaces. Other valid characters might be a hyphen (-) — for example, in the name Smith-Kline — and a single quote (’) — for example, O’Hara. You can
check the name by setting up a pattern that’s a string containing only letters, spaces, hyphens, and single quotes and then matching the name to the pat­ tern. If the name doesn’t match — that is, if it contains characters not in the pattern, such as numerals or a question mark (?) — it’s not a real name.

Patterns consist of literal characters and special characters. Literal characters are normal characters, with no other special meaning. A c is a c with no meaning other than it’s one of the 26 letters in the English alphabet. Special characters have special meaning in the pattern, such as the asterisk (*) when used as a wildcard. Table 6-4 shows the special characters used in patterns.

Literal and special characters are combined to make patterns, which are sometimes long, complicated patterns. A string is compared to the pattern, and if it matches, the comparison is true. Some example patterns follow with a breakdown of the pattern and some sample matching and nonmatching strings:

^[A-Z].* — Strings that begin with an uppercase letter

• ^[A-Z] — Uppercase letter at the beginning of the string

• .* — A string of characters that is one or more characters long

Strings that match:

• Play it again, Sam

• I

Strings that do not match:

• play it again, Sam

• i

Dear (son|daughter) — Two alternate strings

• Dear — Literal characters

• (son|daughter) — Either son or daughter Strings that match:
• Dear son

• My Dear daughter Strings that do not match:
• Dear Goliath

• son

^[0-9]{5}(\-[0-9]{4})?$ — Any ZIP code

• ^[0-9]{5} — Any string of five numbers

• \- — A literal

• [0-9]{4} — A string of numbers that is four characters long

• ( )? — Groups the last two parts of the pattern and makes them optional

Strings that match:

• 90001

• 90002–4323

Strings that do not match:

• 9001

• 12–4321

^.+@.+\.com$ — Any string with @ embedded that ends in .com

• ^.+ — Any string of one or more characters at the beginning.

• @ — A literal @ (at sign). @ is not a special character.

• .+ — Any string of one or more characters.

• \. — A literal dot.

• com$ — A literal string com at the end of the string. Strings that match:
• mary@hercompany.comStrings that do not match:
• mary@hercompany.net

• @mary.com

You can compare a string to a pattern by using ereg. The general format is

ereg(“pattern”,string);

Either pattern or string can be a literal as follows:

ereg(“[0-9]*”,”1234”);

or can be stored in variables, as follows:

ereg($pattern,$string);

To use ereg to check the name that a user typed in a form, compare the name to a pattern as follows:

ereg(“^[A-Za-z’ -]+$”,$name)

The pattern in this statement does the following:

Uses ^ and $ to signify the beginning and end of the string. That means that all the characters in the string must match the pattern.

Encloses all the literal characters that are allowed in the string in [ ]. No other characters are allowed. The allowed characters are uppercase and lowercase letters, an apostrophe (‘), a blank space, and a hyphen (-).

You can specify a range of characters using a hyphen within the [ ]. When you do that, as in A-Z above, the hyphen does not represent a lit­ eral character. Because you want the hyphen included as a literal char­ acter that is allowed in your string, you need to add a hyphen that is not between any two other characters. In this case, the hyphen is included
at the end of the list of literal characters.

Follows the list of literal characters in the [ ] with a +. The plus sign means that the string can contain any number of the characters inside the [ ] but must contain at least one character.

Joining Comparisons with and/or/xor

Sometimes one comparison is sufficient to check for a condition, but often,
you need to ask more than one question. For instance, suppose that your com­ pany offers catalogs for different products in different languages. You need to know which product the customer wants to see and which language he or she needs to see it in. This is the general format for a series of comparisons:

comparison and|or|xor comparison and|or|xor comparison and|or|xor ...

Comparisons are connected by one of the three following words:

and: Both comparisons are true.

or: One of the comparisons or both of the comparisons are true.

xor: One of the comparisons is true but not both of the comparisons. Table 6-5 shows some examples of multiple comparisons

You can string together as many comparisons as necessary. The comparisons that use and are tested first, the comparisons that use xor are tested next, and the comparisons that use or are tested last. For instance, the following is a condition that includes three comparisons:

$age == 200 or $age == 300 and $name == “Goliath”

If the customer’s name is Goliath and he is 300 years old, this statement is true. The statement is also true if the customer is 200 years old, regardless of what his name is. This condition is not true if the customer is 300 years old, but his name is not Goliath. You get these results because the program checks the condition as follows:

1. The and is compared. The program checks $age to see whether it equals 300, and it checks $name to see whether it equals Goliath. If both match, the condition is true, and the program does not need to check or. If only one or neither of the variables equal the designated value, the testing continues.

2. The or is compared. The program checks $age to see whether it equals
200. If it does, the condition is true. If it does not, the condition is false.

You can change the order in which comparisons are made by using parenthe­ ses. The word inside the parentheses is evaluated first. For instance, you can rewrite the previous statement with parentheses as follows:

( $age == 200 or $age == 300 ) and $name == “Goliath”

The parentheses change the order in which the conditions are checked. Now the or is checked first. This condition is true if the customer’s name is Goliath and he is either 200 or 300 years old. You get these results because the program checks the condition as follows:

1. The or is compared. The program checks $age to see whether it equals either 200 or 300. If it does, this part of the condition is true. However, the comparison on the other side of the and must also be true, so the testing continues.

2. The and is compared. The program checks $name to see whether it equals Goliath. If it does, the condition is true. If it does not, the condi­ tion is false.

Use parentheses liberally, even when you believe that you know the order of the comparisons. Unnecessary parentheses can’t hurt, but comparisons that have unexpected results can.

If you are familiar with other languages, such as C, you may have used ||
(for or) and && (for and) in place of the words. The || and && work in PHP as well. The statement $a < $b && $c > $b is just as valid as the statement
$a < $b and $c > $b. The || is checked before the word or, and the && is checked before the word and.

Adding Comments to Your Program

Comments are notes that are embedded in the program itself. Adding comments in your programs that describe their purpose and what they do is essential. It’s important for the lottery factor; that is, if you win the lottery and run off to a
life of luxury on the French Riviera, someone else will have to finish the applica­ tion. The new person needs to know what your program is supposed to do and how it does it. Actually, comments benefit you as well. You might need to revise the program next year when the details are long buried in your mind under more recent projects.

Use comments liberally. PHP ignores comments; comments are for humans. You can embed comments in your program anywhere as long as you tell PHP that they are comments. The format for comments is

/* comment text
more comment text */

Your comments can be as long or as short as you need. When PHP sees code that indicates the start of a comment (/*), it ignores everything until it sees the code that indicates the end of a comment (*/).

The following is one possible format for comments at the beginning of each program:

/* name: catalog.php
description: Program that displays descriptions of products. The descriptions are stored
in a database. The product descriptions are selected from the database based on
the category the user entered into a form. written by: Lola Designer
created: 2/1/02 modified: 3/15/02
*/

You should use comments throughout the program to describe what the pro­ gram does. Comments are particularly important when the program state­ ments are complicated. Use comments such as the following frequently:

/* Get the information from the database */
/* Check whether the customer is over 18 years old */
/* Add shipping charges to the order total */

PHP also has a short comment format. You can specify that a single line is a comment by using the pound sign (#) or two forward slashes (//) in the fol­ lowing manner:

# This is comment line 1
// This is comment line 2

You can also use # or // in the middle of a line to signal the beginning of a comment. PHP will ignore everything from the # or // to the end of the line. This is useful for commenting a particular statement, as in the following example:

$average = $orderTotal/$nItems // compute average price

Sometimes you really want to emphasize a comment. The following format makes a comment very noticeable:

######################################
## Double-Check This Section ##
######################################

PHP comments are not included in the HTML code that is sent to the user’s browser. The user does not see these comments.

Use comments as often as necessary in the script to make it clear. However, using too many comments is a mistake. Don’t comment every line or everything that you do in the script. If your script is too full of comments, the really impor­ tant comments can get lost in the maze. Only use comments to label sections and to explain code that is unusual or complicated — not code that is obvious.

0 comments: