Search the Catalog
PHP Pocket Reference

PHP Pocket Reference

By Rasmus Lerdorf
1st Edition January 2000
1-56592-769-9, Order Number: 7699
120 pages, $9.95

Introduction

PHP is a server-side, HTML-embedded, cross-platform scripting language--quite a mouthful. In simpler terms, PHP provides a way for you to put instructions in your HTML files to create dynamic content. These instructions are read and parsed by the web server; they never actually make it to the browser that is displaying the page. The web server replaces your PHP code with the content that the code was written to produce.

PHP can be configured to run either as a server module or as a standalone CGI script. At the time of this writing, the server-module version is only production-ready for the Apache web server on Unix systems. The CGI version runs with all web servers on both Unix and Windows 95/98/NT. On the Windows platform (as of PHP Version 4), the server module is being developed to work with ISAPI, NSAPI, and WSAPI, which means the server module will eventually work with Microsoft's IIS, Netscape's Enterprise Server, and O'Reilly's WebSite. See http://www.php.net for availability details.

The PHP language itself borrows concepts from other common languages, such as C and Perl. If you have some experience with one of these languages, you should feel right at home with PHP. In addition to the core language, PHP provides a wide variety of functions that support everything from array manipulation to regular expression support.

Database connectivity is one popular use for PHP. PHP supports a large number of databases natively and many others are accessible through PHP's ODBC functions. Through this database connectivity, it is possible, for example, to take a company's database of products and write a web interface to it using PHP.

This book provides an overview of the core PHP language and contains summaries of all the functions available in PHP. The material covers PHP 3.0.

Installation and Configuration

PHP Version 3 can be installed in two primary ways: as an Apache module on Unix systems or as a CGI script on both Unix and Windows systems. See the installation instructions that come with PHP for full and current information.

When you are using PHP as an Apache module, PHP processing is triggered by a special MIME type. This is defined in the Apache configuration file with a line similar to:

AddType application/x-httpd-php3 .php3

This tells Apache to treat all files that end with the .php3 extension as PHP files, which means that any file with that extension is parsed for PHP tags. The actual extension is completely arbitrary and you are free to change it to whatever you wish to use.

If you are running PHP as a dynamic shared object (DSO) module, you also need this line in your Apache configuration file:

LoadModule php3_module    modules/libphp3.so

When you are running PHP as a CGI script (with any web server), PHP processing is still triggered by this special MIME type, but a bit more work is needed. The web server needs to know that it has to redirect the request for the PHP MIME type to the CGI version of PHP. With ApacheNT, for example, this redirect is done with a set of configuration lines like the following:

ScriptAlias /php3/ "/path-to-php-dir/php.exe" 
AddType application/x-httpd-php3 .php3
Action application/x-httpd-php3 "/php3/php.exe" 

For IIS, this redirect is set up through the Windows registry. Refer to the PHP installation instructions for full details.

At runtime, most aspects of PHP can be controlled with the php3.ini file (located in /usr/local/lib by default). For the Apache module version of PHP, this file is read only when the server is started or reinitialized. Changes to this file should be treated the same as changes to Apache's own configuration files. In other words, if you make a change, you need to send your Apache server an HUB or a USR1 signal before the change will take effect.

Many aspects of PHP can also be controlled on a per-directory basis (or even per-location or per-request) when using the Apache module version. Most of the directives available in the php3.ini file are also available as native Apache directives. The name of a particular directive is the php3.ini name with "php3_" prepended. For a list of all available Apache directives, run your Apache httpd binary with the -h switch.

Embedding PHP in HTML

You embed PHP code into a standard HTML page. For example, here's how you can dynamically generate the title of an HTML document:

<HTML><HEAD><TITLE><?echo $title?></TITLE>
</HEAD>...

The <?echo $title?> portion of the document is replaced by the contents of the $title PHP variable. echo is a basic language statement that you can use to output data.

There are a few different ways that you can embed your PHP code. As you just saw, you can put PHP code between <? and ?> tags:

<? echo "Hello World"; ?>

This style is the most common way to embed PHP, but it is a problem if your PHP code needs to co-exist with XML, as XML may use that tagging style itself. If this is the case, you can turn off this style in the php3.ini file with the short_open_tag directive. Another way to embed PHP code is within <?php and ?> tags:

<?php echo "Hello World"; ?>

This style is always available and is recommended when your PHP code needs to be portable to many different systems. Embedding PHP within <SCRIPT> tags is another style that is always available:

<SCRIPT LANGUAGE="php"> echo "Hello World"; 
</SCRIPT>

One final style, where the code is between <% and %> tags, is disabled by default:

<% echo "Hello World"; %>

You can turn on this style with the asp_tags directive in your php3.ini file. The style is most useful when you are using Microsoft FrontPage or another HTML authoring tool that prefers that tag style for HTML embedded scripts.

You can embed multiple statements by separating them with semicolons:

<? 
echo "Hello World";
echo "A second statement";
?>

It is legal to switch back and forth between HTML and PHP at any time. For example, if you want to output 100 <BR> tags for some reason, you can do it this way:

<? for($i=0; $i<100; $i++) { ?>
<BR>
<? } ?>

When you embed PHP code in an HTML file, you need to use the .php3 file extension for that file, so that your web server knows to send the file to PHP for processing. Or, if you have configured your web server to use a different extension for PHP files, use that extension instead.

When you have PHP code embedded in an HTML page, you can think of that page as being a PHP program. The bits and pieces of HTML and PHP combine to provide the functionality of the program. A collection of pages that contain programs can be thought of as a web application.

Including Files

An important feature of PHP is its ability to include files. These files may contain additional PHP tags. When you are designing a web application, it can be useful to break out some common components and place them in a single file. This makes it much easier to later change certain aspects in one place and have it take effect across the entire application. To include a file, you use the include keyword:

<? 
$title="My Cool Web Application";
include "header.inc"; 
?>

The header.inc file might look as follows:

<HTML><HEAD>
<TITLE><?echo $title?></TITLE>
</HEAD>

This example illustrates two important concepts of included files in PHP. First, variables set in the including file are automatically available in the included file. Second, each included file starts out in HTML mode. In other words, if you want to include a file that has PHP code in it, you have to embed that code just as you would any PHP code.

Language Syntax

Variable names in PHP are case-sensitive. That means that $A and $a are two distinct variables. However, function names in PHP are not case-sensitive. This applies to both built-in functions and user-defined functions.

PHP ignores whitespace between tokens. You can use spaces, tabs, and newlines to format and indent your code to make it more readable. PHP statements are terminated by semicolons.

There are three types of comments in PHP:

/* C style comments */
// C++ style comments
# Bourne shell style comments

The C++ and Bourne shell style comments can be inserted anywhere in your code. Everything from the comment characters to the end of the line is ignored. The C-style comment tells PHP to ignore everything from the start of the comment until the end-comment characters are seen. This means that this style of comment can span multiple lines.

Variables

In PHP, all variable names begin with a dollar sign ($). The $ is followed by an alphabetic character or an underscore, and optionally followed by a sequence of alphanumeric characters and underscores. There is no limit on the length of a variable. Variable names in PHP are case-sensitive. Here are some examples:

$i
$counter
$first_name
$_TMP

In PHP, unlike in many other languages, you do not have to explicitly declare variables. PHP automatically declares a variable the first time a value is assigned to it. PHP variables are untyped; you can assign a value of any type to a variable.

Dynamic Variables

Sometimes it is useful to set and use variables dynamically. Normally, you assign a variable like this:

$var = "hello";

Now let's say you want a variable whose name is the value of the $var variable. You can do that like this:

$$var = "World";

PHP parses $$var by first dereferencing the innermost variable, meaning that $var becomes "hello". The expression that is left is then $"hello", which is just $hello. In other words, we have just created a new variable named hello and assigned it the value "World". You can nest dynamic variables to an infinite level in PHP, although once you get beyond two levels, it can be very confusing for someone who is trying to read your code.

There is a special syntax for using dynamic variables inside quoted strings in PHP:

echo "Hello ${$var}";

This syntax is also used to help resolve an ambiguity that occurs when variable arrays are used. Something like $$var[1] is ambiguous because it is impossible for PHP to know which level to apply the array index to. ${$var[1]} tells PHP to dereference the inner level first and apply the array index to the result before dereferencing the outer level. ${$var}[1], on the other hand, tells PHP to apply the index to the outer level.

Dynamic variables may not initially seem that useful, but there are times when they can shorten the amount of code you need to write to perform certain tasks. For example, say you have an associative array that looks like this:

$array["abc"] = "Hello";
$array["def"] = "World";

Associative arrays like this are returned by various functions in the PHP modules. mysql_fetch_array( ) is one example. The indices in the array usually refer to fields or entity names within the context of the module you are working with. It can be handy to turn these entity names into real PHP variables, so you can refer to them as simply $abc and $def. This can be done as follows:

while(list($index,$value) = each($array)) {
  $$index = $value;
}

Data Types

PHP provides three primitive data types: integers, floating point numbers, and strings. In addition, there are two compound data types: arrays and objects.

Integers

Integers are whole numbers. The range of integers in PHP is equivalent to the range of the long data type in C. On 32-bit platforms, integer values can range from -2,147,483,648 to +2,147,483,647. PHP automatically converts larger values to floating point numbers if you happen to overflow the range. An integer can be expressed in decimal (base-10), hexadecimal (base-16), or octal (base-8). For example:

$decimal=16; 
$hex=0x10; 
$octal=020; 

Floating Point Numbers

Floating point numbers represent decimal values. The range of floating point numbers in PHP is equivalent to the range of the double type in C. On most platforms a double can range from 1.7E-308 to 1.7E+308. A double may be expressed either as a regular number with a decimal point or in scientific notation. For example:

$var=0.017; 
$var=17.0E-3

Note that PHP also has a set of functions known as the BC (binary calculator) functions. These functions can manipulate arbitrary precision numbers. If you are dealing with very large numbers or numbers that require a high degree of precision, you should use these functions.

Strings

A string is a sequence of characters. A string can be delimited by single quotes or double quotes:

'PHP is cool'
"Hello, World!"

Double-quoted strings are subject to variable substitution and escape sequence handling, while single quotes are not. For example:

$a="World"; 
echo "Hello\t$a\n";

This displays "Hello" followed by a tab and then "World" followed by a newline. In other words, variable substitution is performed on the variable $a and the escape sequences are converted to their corresponding characters. Contrast that with:

echo 'Hello\t$a\n';

In this case, the output is exactly "Hello\t$a\n". There is no variable substitution or handling of escape sequences.

The following table shows the escape sequences understood by PHP:

Escape Sequence

Meaning

\n

Newline

\t

Tab

\r

Carriage return

\\

Backslash

\$

Dollar sign

Arrays

An array is a compound data type that can contain multiple data values, indexed either numerically or with strings. For example, an array of strings can be written like this:

$var[0]="Hello";
$var[1]="World";

Note that when you assign array elements like this, you do not have to use consecutive numbers to index the elements.

As a shortcut, PHP allows you to add an element onto the end of an array without specifying an index. For example:

$var[] ="Test";

PHP picks the next logical numerical index. In this case, the "Test" element is given the index 2 in our $var array: if the array has non-consecutive elements, PHP selects the index value that is one greater than the current highest index value. This auto-indexing feature is most useful when dealing with multiple-choice HTML <SELECT> form elements, as we'll see in a later example.

Although we have called strings a primitive data type, it is actually possible to treat a string as a compound data type, where each character in the string can be accessed separately. In other words, you can think of a string as an array of characters, where the first character is at index 0. Thus, you can pick the third character out of a string with:

$string[2]

Arrays can also be indexed using strings; these kinds of arrays are called associative arrays :

$var["January"]=1;
$var["February"]=2;

In fact, you can use a mix of numerical and string indices with a single array. That is because internally PHP treats all arrays as hash tables and the hash, or index, can be whatever you want.

All arrays in PHP can be traversed safely with the following mechanism:

while(list($key,$value)=each($array)) {
 echo "array[$key]=$value<br>\n";
}

This is the most common way to loop through each element of an array, whether it is a linear or an associative array. PHP provides a number of array manipulation functions; these are detailed later in the "Function Reference" section.

Objects

An object is a compound data type that can contain any number of variables and functions. PHP's support for objects is very basic in Version 3. PHP Version 4 will improve the object-oriented capabilities of PHP. In PHP 3.0 the object-oriented support is designed to make it easy to encapsulate data structures and functions in order to package them into reusable classes. Here's a simple example:

class test {
 var $str = "Hello World";
 function init($str) {
  $this->str = $str;
 }
}
 
$class = new test;
print $class->str;
$class->init("Hello");
print $class->str;

This code creates a test object using the new operator. Then it sets a variable called str within the object. In object-speak, a variable in an object is known as a property of that object. The test object also defines a function, known as a method, called init( ). This method uses the special-purpose $this variable to change the value of the str property within that object.

If you are familiar with object-oriented programming, you should recognize that PHP's implementation is minimal. PHP3 does not support multiple inheritance, data protection (or encapsulation), and destructors. PHP does have inheritance and constructors, though.

Boolean Values

Every value in PHP has a boolean truth value (true or false) associated with it. This value is typically used in control structures, like if/else and for. The boolean value associated with a data value is determined as follows:

PHP has two built-in keywords, true and false, where true represents the integer value 1 and false represents the empty string.

Type Casting

Variables in PHP do not need to be explicitly typed. PHP sets the type when a variable is first used in a script. You can explicitly specify a type using C-style casting.

For example:

$var = (int) "123abc";

Without the (int) in this example, PHP creates a string variable. With the explicit cast, however, we have created an integer variable with a value of 123. The following table shows the available cast operators in PHP:

Operators

Function

(int), (integer)

Cast to an integer

(real), (double), (float)

Cast to a floating point number

(string)

Cast to a string

(array)

Cast to an array

(object)

Cast to an object

Although they are not usually needed, PHP does provide the following built-in functions to check variable types in your program: gettype( ), is_long( ), is_double( ), is_string( ), is_array( ), and is_object( ).

Expressions

An expression is the basic building block of the language. Anything with a value can be thought of as an expression. Examples include:

5
5+5
$a
$a==5
sqrt(9)

By combining many of these basic expressions, you can build larger and more complex expressions.

Note that the echo statement we've used in numerous examples cannot be part of a complex expression because it does not have a return value. The print statement, on the other hand, can be used as part of complex expression, as it does have a return value. In all other respects, echo and print are identical--they output data.

Operators

Expressions are combined and manipulated using operators. The following table shows the operators available in PHP, along with their precedence (P) and associativity (A). The following table lists the operators from highest to lowest precedence. These operators should be familiar to you if you have any C, Java, or Perl experience.

Operators

P

A

!, ~, ++, --, @, (the casting operators)

16

Right

*, /, %

15

Left

+, - .

14

Left

<<, >>

13

Left

<, <=, >=, >

12

Non-associative

==, !=

11

Non-associative

&

10

Left

^

9

Left

|

8

Left

&&

7

Left

||

6

Left

? : (conditional operator)

5

Left

=, +=, -=, *=, /=, %=, ^=, .=, &=, |=

4

Left

And

3

Left

Xor

2

Left

Or

1

Left

Control Structures

The control structures in PHP are very similar to those used by the C language. Control structures are used to control the logical flow through a PHP script. PHP's control structures have two syntaxes that can be used interchangeably. The first form uses C-style curly braces to enclose statement blocks, while the second style uses a more verbose syntax that includes explicit ending statements. The first style is preferable when the control structure is completely within a PHP code block. The second style is useful when the construct spans a large section of intermixed code and HTML. The two styles are completely interchangeable, however, so it is really a matter of personal preference which one you use.

if

The if statement is a standard conditional found in most languages. Here are the two syntaxes for the if statement:

if(expr) {	    if(expr):
 statements	     statements
}	            elseif(expr):
elseif(expr) {	     statements
 statements	    else:
}	             statements
else {	            endif;
 statements             
}                  

The if statement causes particular code to be executed if the expression it acts on is true. With the first form, you can omit the braces if you only need to execute a single statement.

switch

The switch statement can be used in place of a lengthy if statement. Here are the two syntaxes for switch:

switch(expr) {         switch(expr):
 case expr:             case expr:
  statements              statements
  break;                 break;
 default:               default:
  statements              statements
  break;                 break;
}                      endswitch;

The expression for each case statement is compared against the switch expression and, if they match, the code following that particular case is executed. The break keyword signals the end of a particular case; it may be omitted, which causes control to flow into the next case. If none of the case expressions match the switch expression, the default case is executed.

while

The while statement is a looping construct that repeatedly executes some code while a particular expression is true:

while(expr) {         while(expr):
 statements             statements
}                     endwhile; 

The while expression is checked before the start of each iteration. If the expression evaluates to true, the code within the loop is executed. If the expression evaluates to false, however, execution skips to the code immediately following the while loop. Note that you can omit the curly braces with the first form of the while statement if you only need to execute a single statement.

It is possible to break out of a running loop at any time using the break keyword. This stops the current loop and, if control is within a nested set of loops, the next outer loop continues. It is also possible to break out of many levels of nested loops by passing a numerical argument to the break statement (break n) that specifies the number of nested loops it should break out of. You can skip the rest of a given loop and go onto the next iteration by using the continue keyword. With continue n, you can skip the current iterations of the n innermost loops.

do/while

The do/while statement is similar to the while statement, except that the conditional expression is checked at the end of each iteration instead of before it:

do { 
 statements
} while(expr);

Note that due to the order of the parts of this statement, there is only one valid syntax. If you only need to execute a single statement, you can omit the curly braces from the syntax. The break and continue statements work with this statement in the same way that they do with the while statement.

for

A for loop is a more complex looping construct than the simple while loop:

for(start_expr; cond_expr; iter_expr) {
 statements
}
 
for(start_expr; cond_expr; iter_expr): 
 statements
endfor;

A for loop takes three expressions. The first is the start expression; it is evaluated once when the loop begins. This is generally used for initializing a loop counter. The second expression is a conditional expression that controls the iteration of the loop. This expression is checked prior to each iteration. The third expression, the iterative expression, is evaluated at the end of each iteration and is typically used to increment the loop counter. With the first form of the for statement, you can omit the braces if you only need to execute a single statement.

The break and continue statements work with a for loop like they do with a while loop, except that continue causes the iterative expression to be evaluated before the loop conditional expression is checked.

Functions

A function is a named sequence of code statements that can optionally accept parameters and return a value. A function call is an expression that has a value; its value is the returned value from the function. PHP provides a large number of internal functions. The "Function Reference" section lists all of the commonly available functions. PHP also supports user-definable functions. To define a function, use the function keyword. For example:

function soundcheck($a, $b, $c) {
 return "Testing, $a, $b, $c";
}

When you define a function, you need to be careful what name you give it. In particular, you need to make sure that the name does not conflict with any of the internal PHP functions. If you do use a function name that conflicts with an internal function, you get the following error:

Fatal error: Can't redeclare already declared function in filename on line N

After you define a function, you call it by passing in the appropriate arguments. For example:

echo soundcheck(4, 5, 6);

You can also create functions with optional parameters. To do so, you set a default value for each optional parameter in the definition, using C++ style. For example, here's how to make all the parameters to the soundcheck( ) function optional:

function soundcheck($a=1, $b=2, $c=3) {
 return "Testing, $a, $b, $c";
}

Variable Scope

The scope of a variable refers to where in a program the variable is available. If a variable is defined in the main part of a PHP script (i.e., not inside a function or a class), it is in the global scope. Note that global variables are only available during the current request. The only way to make variables in one page available to subsequent requests to another page is to pass them to that page via cookies, GET method data, or PUT method data. To access a global variable from inside a function, you need to use the global keyword. For example:

function test(  ) {
 global $var;
 echo $var;
}
$var="Hello World";
test(  );

The $GLOBALS array is an alternative mechanism for accessing variables in the global scope. This is an associative array of all the variables currently defined in the global scope:

function test(  ) {
 echo $GLOBALS["var"];
}
$var="Hello World";
test(  );

Every function has its own scope. When you create a variable inside of a function, that variable has local scope. In other words, it is only available within the function. In addition, if there is a global variable with the same name as a variable within a function, any changes to the function variable do not affect the value of the global variable.

When you call a function, the arguments you pass to the function (if any) are defined as variables within the function, using the parameter names as variable names. Just as with variables created within a function, these passed arguments are only available within the scope of the function.

Passing Arguments

There are two ways you can pass arguments to a function: by value and by reference. To pass an argument by value, you pass in any valid expression. That expression is evaluated and the value is assigned to the corresponding parameter defined within the function. Any changes you make to the parameter within the function have no effect on the argument passed to the function. For example:

function triple($x) {
 $x=$x*3;
 return $x;
}
$var=10;
$triplevar=triple($var);

In this case, $var evaluates to 10 when triple( ) is called, so $x is set to 10 inside the function. When $x is tripled, that change does not affect the value of $var outside the function.

In contrast, when you pass an argument by reference, changes to the parameter within the function do affect the value of the argument outside the scope of the function. That's because when you pass an argument by reference, you must pass a variable to the function. Now the parameter in the function refers directly to the value of the variable, meaning that any changes within the function are also visible outside the function. For example:

function triple($x) {
 $x=$x*3;
 return $x;
}
$var=10;
triple(&$var);

The & that precedes $var in the call to triple( ) causes the argument to be passed by reference, so the end result is that $var ends up with a value of 30.

Static Variables

PHP supports declaring local function variables as static. A static variable retains its value between function calls, but is still accessible only from within the function it is declared in. Static variables can be initialized and this initialization only takes place the first time the static declaration is executed. Static variables are often used as counters, as in this example:

function hitcount(  ) 
 static $count = 0;
 
 if ($count == 0) {
  print "This is the first time this page";
  print " has been accessed";
 } 
 else {
  print "This page has been accessed $count";
  print  " times";
 }
 $count++;
}

Web-Related Variables

PHP automatically creates global variables for all the data it receives in an HTTP request. This can include GET data, POST data, cookie data, and environment variables. Say you have an HTML form that looks as follows:

<FORM ACTION="test.php3" METHOD="POST">
<INPUT TYPE=text NAME=var>
</FORM>

When the form is submitted to the test.php3 file, the $var variable within that file is set to whatever the user entered in the text field.

A variable can also be set in a URL like this:

http://your.server/test.php3?var=Hello+World

When the request for this URL is processed, the $var variable is set for the test.php3 page.

Any environment variables present in your web server's configuration are also made available, along with any CGI-style variables your web server might set. The actual set of variables varies between different web servers. The best way to get a list of these variables is to use PHP's special information tag. Put the following code in a page and load the page in your browser:

<? phpinfo(  ) ?>

You should see a page with quite a bit of information about PHP and the machine it is running on. There is a table that describes each of the extensions currently enabled in PHP. Another table shows the current values of all the various configuration directives from your php3.ini file. Following those two tables are more tables showing the regular environment variables, the special PHP internal variables, and the special environment variables that your web server has added. Finally, the HTTP request and response headers for the current request are shown.

Sometimes it is convenient to create a generic form handler, where you don't necessarily know all the form element names. To support this, PHP provides GET, POST, and cookie associative arrays that contain all of the data passed to the page using the different techniques. These arrays are named $HTTP_GET_DATA, $HTTP_POST_DATA, $HTTP_COOKIE_DATA, respectively. For example, here's another way to access the value of the text field in our form:

echo $HTTP_POST_VARS["var"];

PHP sets global variables in a particular order. By default, global variables are set first from GET data, then from POST data, and then finally from cookie data. This means that if you have a form with a field named var that uses the GET method and a cookie with a var value, there is just one global variable named $var that has the value of the cookie data. Of course, you can still get at the GET data through the $HTTP_GET_DATA array. The default order can be defined with the gpc_order directive in the php3.ini file.

Examples

The best way to understand the power of PHP is to examine some real examples of PHP in action, so we'll look at some common uses of PHP in this section.

Showing the Browser and IP Address

Here is a simple page that prints out the browser string and the IP address of the HTTP request. Create a file with the following content in your web directory, name it something like example.php3, and load it in your browser:

<HTML><HEAD><TITLE>PHP Example</TITLE></HEAD>
<BODY>
You are using <? echo $HTTP_USER_AGENT ?><BR>
and coming from <? echo $REMOTE_ADDR ?>
</BODY></HTML>

You should see something like the following in your browser window:

You are using Mozilla/4.0 (compatible; MSIE 4.01; Windows 98) 
and coming from 207.164.141.23

Intelligent Form Handling

Here is a slightly more complex example. We are going to create an HTML form that asks the user to enter a name and select one or more interests from a selection box. We could do this in two files, where we separate the actual form from the data handling code, but instead, this example shows how it can be done in a single file:

<HTML><HEAD><TITLE>Form Example</TITLE></HEAD>
<BODY>
<H1>Form Example</h2>
<?
function show_form($first="", $last="",
                   $interest=""){
 $options = array("Sports", "Business",
                  "Travel", "Shopping",
                  "Computers");
 if(empty($interest)) $interest=array(-1);
?>
<FORM ACTION="form.php3" METHOD="POST">
First Name: 
<INPUT TYPE=text NAME=first 
       VALUE="<?echo $first?>">
<BR>
Last Name: 
<INPUT TYPE=text NAME=last 
       VALUE="<?echo $last?>">
<BR>
Interests: 
<SELECT MULTIPLE NAME=interest[]>
<? 
 for($i=0, reset($interest); 
     $i<count($options); $i++){
  echo "<OPTION";
  if(current($interest)==$options[$i]) {
   echo " SELECTED ";
   next($interest);
  }
  echo "> $options[$i]\n";
 }
?>
</SELECT><BR>
<INPUT TYPE=submit>
</FORM>
<? }
 
if(!isset($first)) {
 show_form();
} 
else {
 if(empty($first) || empty($last) || 
  count($interest) == 0) {
  echo "You did not fill in all the ";
  echo "fields, please try again<P>\n";
  show_form($first,$last,$interests);
 } 
 else { 
  echo "Thank you, $first $last, you ";
  echo "selected ". join(" and ", $interest);
  echo " as your interests.<P>\n";
 }
}
?>
</BODY></HTML>

There are a few things you should study carefully in this example. First, we have isolated the display of the actual form to a PHP function called show_form( ). This function is intelligent in that it can take the default value for each of the form elements as an optional argument. If the user does not fill in all the form elements, we use this feature to redisplay the form with whatever values the user has already entered. This means that the user only has to fill the fields he missed, which is much better than asking the user to hit the Back button or forcing him to reenter all the fields.

Notice how the file switches back and forth between PHP code and HTML. Right in the middle of defining our show_form( ) function, we switch back to HTML to avoid having numerous echo statements that just echo normal HTML. Then, when we need a PHP variable, we switch back to PHP code temporarily just to print the variable.

We've given the multiple-choice <SELECT> element the name interest[]. The [] on the name tells PHP that the data coming from this form element should be treated as an auto-indexed array. This means that PHP automatically gives each element the next sequential index, starting with 0 (assuming the array is empty to begin with).

The final thing to note is the way we determine what to display. We check if $first is set. If it isn't, we know that the user has not submitted the form yet, so we call show_form( ) without any arguments. This displays the empty form. If $first is set, however, we check to make sure that the $first and $last text fields are not empty and that the user has selected at least one interest.

Web Database Integration

To illustrate a complete database-driven application, we are going to build a little web application that lets people make suggestions and vote on what you should name your new baby. The example uses MySQL, but it can be changed to run on any of the databases that PHP supports.

The schema for our baby-name database looks like this:

CREATE TABLE baby_names (
 name varchar(30) NOT NULL,
 votes int(4),
 PRIMARY KEY (name)
);

This is in MySQL's query format and can be used directly to create the actual table. It simply defines a text field and an integer field. The text field is for the suggested baby name and the integer field is for the vote count associated with that name. We are making the name field a primary key, which means uniqueness is enforced, so that the same name cannot appear twice in the database.

We want this application to do a number of things. First, it should have a minimal check that prevents someone from voting many times in a row. We do this using a session cookie. Second, we want to show a fancy little barchart that depicts the relative share of the votes that each name has received. The barchart is created using a one pixel by one pixel blue dot GIF image and scaling the image using the height and width settings of the HTML <IMG> tag. We could also use PHP's built-in image functions to create a fancier looking bar.

Everything else is relatively straightforward form and database work. We use a couple of shortcuts as well. For example, instead of reading all the entries from the database and adding up all the votes in order to get a sum (which we need to calculate the percentages), we ask MySQL to do it for us with its built-in SUM function. The part of the code that displays all the names and their votes, along with the percentage bar, gets a little ugly, but you should be able to follow it. We are simply sending the correct HTML table tags before and after the various data we have fetched from the database.

Here's the full example:

<? 
  if($vote && !$already_voted) 
    SetCookie("already_voted","1");
?>
<HTML><HEAD><TITLE>Name the Baby</TITLE>
</HEAD><H3>Name the Baby</H3>
<FORM ACTION="baby.php3" METHOD="POST">
Suggestion: <INPUT TYPE=text NAME=new_name><P>
<INPUT TYPE=submit 
       VALUE="Submit idea and/or vote">
<?
 mysql_pconnect("localhost","","");
 $db = "test";
 $table = "baby_names";
 
 if($new_name) {
  if(!mysql_db_query($db,
   "insert into $table values 
    ('$new_name',0)")) {
    echo mysql_errno().": ";
    echo mysql_error()."<BR>";
  }
 }
 if($vote && $already_voted) {
  echo "<FONT COLOR=#ff0000>Hey, you voted ";
  echo "already! Vote ignored.</FONT><P>\n";
 }
 else if($vote) {
  if(!mysql_db_query($db,
   "update $table set votes=votes+1 
    where name='$vote'")) {
   echo mysql_errno().": ";
   echo mysql_error()."<BR>";
  }
 }
 $result=mysql_db_query($db,
  "select sum(votes) as sum from $table");
 if($result) {
  $sum = (int) mysql_result($result,0,"sum");
  mysql_free_result($result);
 }
 
 $result=mysql_db_query($db,
  "select * from $table order by votes DESC");
 echo "<TABLE BORDER=0><TR><TH>Vote</TH>";
 echo "<TH>Idea</TH><TH COLSPAN=2>Votes</TH>";
 echo "</TR>\n";
 while($row=mysql_fetch_row($result)) {
  echo "<TR><TD ALIGN=center>";
  echo "<INPUT TYPE=radio NAME=vote ";
  echo "VALUE='$row[0]'></TD><TD>";
  echo $row[0]."</TD><TD ALIGN=right>";
  echo $row[1]."</TD><TD>";
  if($sum && (int)$row[1]) {
   $per = (int)(100 * $row[1]/$sum);
   echo "<IMG SRC=bline.gif HEIGHT=12 ";
   echo "WIDTH=$per> $per %</TD>";
  }
  echo "</TR>\n";
 }
 echo "</TABLE>\n";
 mysql_free_result($result);
?>
<INPUT TYPE=submit 
       VALUE="Submit idea and/or vote">
<INPUT TYPE=reset>
</FORM>
</BODY></HTML>

Back to: PHP Pocket Reference


oreilly.com Home | O'Reilly Bookstores | How to Order | O'Reilly Contacts
International | About O'Reilly | Affiliated Companies | Privacy Policy

© 2001, O'Reilly & Associates, Inc.