O'Reilly logo

Learning PHP 5 by David Sklar

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

PHP in Action

Ready for your first taste of PHP? This section contains a few program listings and explanations of what they do. If you don't understand everything going on in each listing, don't worry! That's what the rest of the book is for. Read these listings to get a sense of what PHP programs look like and an outline of how they work. Don't sweat the details yet.

When given a program to run, the PHP interpreter pays attention only to the parts of the program between PHP start and end tags. Whatever's outside those tags is printed with no modification. This makes it easy to embed small bits of PHP in pages that mostly contain HTML. The PHP interpreter runs the commands between <?php (the PHP start tag) and ?> (the PHP end tag). PHP pages typically live in files whose names end in .php. Example 1-1 shows a page with one PHP command.

Example 1-1. Hello, World!

<html>
<head><title>PHP says hello</title></head>
<body>
<b>
<?php
print "Hello, World!";
?>
</b>
</body> 
</html>

The output of Example 1-1 is:

<html>
<head><title>PHP says hello</title></head>
<body>
<b>
Hello, World!
</b>
</body> 
</html>

In your web browser, this looks like Figure 1-3.

Saying hello with PHP

Figure 1-3. Saying hello with PHP

Printing a message that never changes is not a very exciting use of PHP, however. You could have included the "Hello, World!" message in a plain HTML page with the same result. More useful is printing dynamic data — i.e., information that changes. One of the most common sources of information for PHP programs is the user: the browser displays a form, the user enters information into that and hits the "submit" button, the browser sends that information to the server, and the server finally passes it on to the PHP interpreter where it is available to your program.

Example 1-2 is an HTML form with no PHP. The form consists simply of a text box named user and a Submit button. The form submits to sayhello.php, specified via the <form> tag's action attribute.

Example 1-2. HTML form for submitting data

<form method="POST" action="sayhello.php">
Your Name: <input type="text" name="user"/>
<br/>
<input type="submit" value="Say Hello"/>
</form>

Your web browser renders the HTML in Example 1-2 into the form shown in Figure 1-4.

Printing a form

Figure 1-4. Printing a form

Example 1-3 shows the sayhello.php program that prints a greeting to whomever is named in the form's text box.

Example 1-3. Dynamic data

<?php
print "Hello, ";
// Print what was submitted in the form parameter called 'user'
print $_POST['user'];
print "!";
?>

If you type Ellen in the text box and submit the form, then Example 1-3 prints Hello, Ellen!. Figure 1-5 shows how your web browser displays that.

Printing a form parameter

Figure 1-5. Printing a form parameter

$_POST holds the values of submitted form parameters. In programming terminology, it is a variable, so called because you can change the values it holds. In particular, it is an array variable, because it can hold more than one value. This particular array is discussed in Chapter 6. Arrays are discussed in Chapter 4.

In this example, the line that begins with // is called a comment line. Comment lines are there for human readers of source code and are ignored by the PHP interpreter. Comments are useful for annotating your programs with information about how they work. Section 1.4.3, later in this chapter, discusses comments in more detail.

You can also use PHP to print out the HTML form that lets someone submit a value for user. This is shown in Example 1-4.

Example 1-4. Printing a form

<?php
print <<<_HTML_
<form method="post" action="$_SERVER[PHP_SELF]">
Your Name: <input type="text" name="user">
<br/>
<input type="submit" value="Say Hello">
</form>
_HTML_;
?>

Example 1-4 uses a string syntax called a here document. Everything between the <<<_HTML_ and the _HTML_ is passed to the print command to be displayed. Just like in Example 1-3, a variable inside the string is replaced with its value. This time, the variable is $_SERVER[PHP_SELF]. This is a special PHP variable that contains the URL (without the protocol or hostname) of the current page. If the URL for the page in Example 1-4 is http://www.example.com/users/enter.php, then $_SERVER[PHP_SELF] contains /users/enter.php.

With $_SERVER[PHP_SELF] as the form action, you can put the code for printing a form and for doing something with the submitted form data in the same page. Example 1-5 combines Examples Example 1-3 and Example 1-4 into one page that displays a form and prints a greeting when the form is submitted.

Example 1-5. Printing a greeting or a form

<?php
// Print a greeting if the form was submitted
if ($_POST['user']) {
    print "Hello, ";
    // Print what was submitted in the form parameter called 'user'
    print $_POST['user'];
    print "!";
} else {
    // Otherwise, print the form
    print <<<_HTML_
<form method="post" action="$_SERVER[PHP_SELF]">
Your Name: <input type="text" name="user">
<br/>
<input type="submit" value="Say Hello">
</form>
_HTML_;
}
?>

Example 1-5 uses the if( ) construct to see whether the browser sent a value for the form parameter user. It uses that to decide which of two things to do: print a greeting or print a form. Chapter 3 talks about if( ). Using $_SERVER[PHP_SELF] and processing forms is discussed in Chapter 6.

PHP has a huge library of internal functions that you can use in your programs. These functions help you accomplish common tasks. One built-in function is number_format( ) , which provides a formatted version of a number. Example 1-6 uses number_format( ) to print out a number.

Example 1-6. Printing a formatted number

<?php print "The population of the US is about:";
print number_format(285266237);
?>

Example 1-6 prints:

The population of the US is about: 285,266,237

Chapter 5 is about functions. It shows you how to write your own and explains the syntax for calling and handling the results of functions. Many functions, including number_format( ), have a return value. This is the result of running the function. In Example 1-6, the data that second print statement is given to print is the return value from number_format( ). In this case, it's the the comma-formatted population number.

One of the most common types of programs written in PHP is one that displays a web page containing information retrieved from a database. When you let submitted form parameters control what is pulled from the database, you open the door to a universe of interactivity on your web site. Example 1-7 shows a PHP program that connects to a database server, retrieves a list of dishes and their prices based on the value of the form parameter meal, and prints those dishes and prices in an HTML table.

Example 1-7. Displaying information from a database

<?php
require 'DB.php';
// Connect to MySQL running on localhost with username "menu"
// and password "good2eaT", and database "dinner"
$db = DB::connect('mysql://menu:good2eaT@localhost/dinner');
// Define what the allowable meals are
$meals = array('breakfast','lunch','dinner');
// Check if submitted form parameter "meal" is one of
// "breakfast", "lunch", or "dinner"
if (in_array($meals, $_POST['meal'])) {
    // If so, get all of the dishes for the specified meal
    $q = $db->query("SELECT dish,price FROM meals WHERE meal LIKE '" . 
                     $_POST['meal'] ."'");
    // If no dishes were found in the database, say so
    if ($q->numrows == 0) {
        print "No dishes available.";
    } else {
        // Otherwise, print out each dish and its price as a row
        // in an HTML table
        print '<table><tr><th>Dish</th><th>Price</th></tr>';
        while ($row = $q->fetchRow( )) {
            print "<tr><td>$row[0]</td><td>$row[1]</td></tr>";
        }
        print "</table>";
    }
} else {
    // This message prints if the submitted parameter "meal" isn't
    // "breakfast", "lunch", or "dinner"
    print "Unknown meal.";
}
?>

There's a lot going on in Example 1-7, but it's a testament to the simplicity and power of PHP that it takes only about 15 lines of code (without comments) to make this dynamic, database-backed web page. The following describes what happens in those 15 lines.

The DB::connect( ) function at the top of the example sets up the connection to the MySQL database with appropriate authentication information such as a username and a password. These functions, like the other database functions used in this example (query( ), numrows( ), and fetchRow( )), are explained in more detail in Chapter 7.

Things in the program that begin with a $, such as $db, $_POST, $q, and $row, are variables. Variables hold values that may change as the program runs or that are created at one point in the program and are saved to use later. Chapter 2 talks about variables.

After connecting to the database, the next task is to see what meal the user requested. The $meals array is initialized to hold the allowable meals: breakfast, lunch, and dinner. The statement in_array($meals, $POST['meal']) checks whether the submitted form parameter meal (the value of $_POST['meal']) is in the $meals array. If not, execution skips down to the end of the example, after the last else, and prints Unknown meal.

If an acceptable meal was submitted, query( ) sends a query to the database. For example, if the meal is breakfast, the query that is sent is as follows:

SELECT dish,price FROM meals WHERE meal LIKE 'breakfast'

Queries to MySQL and most other databases are written in a language called Structured Query Language (SQL). Chapter 7 provides the basics of SQL. The query( ) function returns an identifier that we can use to get further information about the query.

The numrows( ) function uses that identifier to see how many matching meals the query found in the database. If there are no applicable meals, the program prints No dishes available. Otherwise, it displays information about the matching meals.

The program prints the beginning of the HTML table. Then, it uses the fetchRow( ) function to retrieve each dish that the query found. The print statement uses elements of the array returned by fetchRow( ) to display one table row per dish.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required