Article
Build Your Own Database Driven Web Site using PHP & MySQL, Part 3: Introducing PHP
In Chapter 1: Installation, we installed and set up two software programs: the Apache web server with PHP, and the MySQL database server. In Chapter 2: Introducing MySQL, I showed you how to work with MySQL databases using Structured Query Language (SQL). Now, here’s where the fun really starts. In this chapter, I’ll introduce you to the PHP scripting language, which you can use to build dynamic web pages that present up-to-the-moment information to your visitors.
If you'd rather read this tutorial offline, you can download the chapters in PDF format.
PHP is a server-side language. This concept may be a little difficult to grasp, especially if you’re used to designing pages using only client-side languages like HTML, CSS, and JavaScript.
A server-side language is similar to JavaScript in that it allows you to embed little programs (scripts) into the HTML code of a web page. When executed, these programs give you greater control over what appears in the browser window than HTML alone can provide. The key difference between JavaScript and PHP is the stage of loading the web page at which these embedded programs are executed.
Client-side languages like JavaScript are read and executed by the web browser, after downloading the web page (embedded programs and all) from the web server. In contrast, server-side languages like PHP are run by the web server, before sending the web page to the browser. Whereas client-side languages give you control over how a page behaves once it’s displayed by the browser, server-side languages let you generate customized pages on the fly before they’re even sent to the browser.
Once the web server has executed the PHP code embedded in a web page, the results of that code’s execution take the place of the PHP code in the page. When the browser receives the page, all it sees is standard HTML code, hence the name: server-side language. Let’s look back at the today.php example presented in Chapter 1, Installation:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Today’s Date</title>
<meta http-equiv="content-type"
content="text/html; charset=utf-8"/>
</head>
<body>
<p>Today’s date (according to this web server) is
<?php
echo date('l, F dS Y.');
?>
</p>
</body>
</html>
Most of this is plain HTML; however, the line between <?php and ?> is PHP code. <?php marks the start of an embedded PHP script and ?> marks the end of such a script. The web server is asked to interpret everything between these two delimiters, and to convert it to regular HTML code before it sends the web page to the requesting browser. The browser is presented with the following:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Today’s Date</title>
<meta http-equiv="content-type"
content="text/html; charset=utf-8"/>
</head>
<body>
<p>Today’s Date (according to this web server) is
Wednesday, April 1st 2009. </p>
</body>
</html>
Notice that all signs of the PHP code have disappeared. In its place, the output of the script has appeared, and it looks just like standard HTML. This example demonstrates several advantages of server-side scripting:
No browser compatibility issues
PHP scripts are interpreted by the web server alone, so there’s no need to worry about whether the language you’re using is supported by the visitor’s browser.
Access to server-side resources
In the above example, we placed the date, according to the web server, into the web page. If we had inserted the date using JavaScript, we’d only be able to display the date according to the computer on which the web browser was running. Granted, there are more impressive examples of the exploitation of server-side resources; a better example might be inserting content pulled out of a MySQL database (hint, hint …).
Reduced load on the client
JavaScript can delay the display of a web page on slower computers significantly, as the browser must run the script before it can display the web page. With server-side code, this burden is passed to the web server machine, which you can make as beefy as your application requires.
Basic Syntax and Statements
PHP syntax will be very familiar to anyone with an understanding of C, C++, C#, Java, JavaScript, Perl, or any other C-derived language. If you’re unfamiliar with any of these languages, or if you’re new to programming in general, there’s no need to worry about it!
A PHP script consists of a series of commands, or statements. Each statement is an instruction that must be followed by the web server before it can proceed to the next. PHP statements, like those in the above-mentioned languages, are always terminated by a semicolon (;).
This is a typical PHP statement:
echo 'This is a <strong>test</strong>!';
This is an echo statement, which is used to generate content (usually HTML code) to be sent to the browser. An echo statement simply takes the text it’s given, and inserts it into the page’s HTML code at the position of the PHP script that contains it.
In this case, we have supplied a string of text to be output: 'This is a <strong>test</strong>!'. Notice that the string of text contains HTML tags (<strong> and </strong>), which is perfectly acceptable. So, if we take this statement and put it into a complete web page, here’s the resulting code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Simple PHP Example</title>
<meta http-equiv="content-type"
content="text/html; charset=utf-8"/>
</head>
<body>
<p><?php echo 'This is a <strong>test</strong>!'; ?></p>
</body>
</html>
If you place this file on your web server, a browser that requests the page will receive this:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Simple PHP Example</title>
<meta http-equiv="content-type"
content="text/html; charset=utf-8"/>
</head>
<body>
<p>This is a <strong>test</strong>!</p>
</body>
</html>
The today.php example we looked at earlier contained a slightly more complex echo statement:
echo date('l, F dS Y.');
Instead of giving echo a simple string of text to output, this statement invokes a built-in function called date and passes it a string of text: 'l, F dS Y.'. You can think of built-in functions as tasks that PHP knows how to do without your needing to spell out the details. PHP has many built-in functions that let you do everything from sending email to working with information stored in various types of databases.
When you invoke a function in PHP, you’re said to be calling that function. Most functions return a value when they’re called; PHP then replaces the function call with that value when it executes the statement. In this case, our echo statement contains a call to the date function, which returns the current date as a string of text (the format of which is specified by the text string in the function call). The echo statement therefore outputs the value returned by the function call.
You may wonder why we need to surround the string of text with both parentheses (()) and single quotes (''). As in SQL, quotes are used in PHP to mark the beginning and end of strings of text, so it makes sense for them to be there. The parentheses serve two purposes. First, they indicate that date is a function that you want to call. Second, they mark the beginning and end of a list of parameters (or arguments) that you wish to provide, in order to tell the function what to do. In the case of the date function, you need to provide a string of text that describes the format in which you want the date to appear. A full reference is available in the online documentation for the date function. Later on, we’ll look at functions that take more than one parameter, and we’ll separate those parameters with commas. We’ll also consider functions that take no parameters at all. These functions will still need the parentheses, though it’s unnecessary to type anything between them.
Variables, Operators, and Comments
Variables in PHP are identical to variables in most other programming languages. For the uninitiated, a variable can be thought of as a name that’s given to an imaginary box into which any literal value may be placed. The following statement creates a variable called $testvariable (all variable names in PHP begin with a dollar sign) and assigns it a literal value of 3:
$testvariable = 3;
PHP is a loosely typed language. This means that a single variable may contain any type of data, be it a number, a string of text, or some other kind of value, and may change types over its lifetime. So the following statement, if you were to type it after the statement above, assigns a new value to the existing $testvariable. In the process, the variable changes type: where it used to contain a number, it now contains a string of text:
$testvariable = 'Three';
The equals sign we used in the last two statements is called the assignment operator, as it’s used to assign values to variables. Other operators may be used to perform various mathematical operations on values:
$testvariable = 1 + 1; // Assigns a value of 2
$testvariable = 1 - 1; // Assigns a value of 0
$testvariable = 2 * 2; // Assigns a value of 4
$testvariable = 2 / 2; // Assigns a value of 1
From the above examples, you can probably tell that + is the addition operator, - is the subtraction operator, * is the multiplication operator, and / is the division operator. These are all called arithmetic operators, because they perform arithmetic on numbers.
Each of the lines above ends with a comment. Comments are a way to describe what your code is doing. They insert explanatory text into your code—text that the PHP interpreter will ignore. Comments begin with // and they finish at the end of the same line. If you need a comment to span several lines, you can instead start your comment with /*, and end it with */. The PHP interpreter will ignore everything between these two delimiters. I’ll use comments throughout the rest of this book to help explain some of the code I present.
Returning to the operators, there’s another one that sticks strings of text together, called the string concatenation operator:
$testvariable = 'Hi ' . 'there!'; // Assigns a value of 'Hi there!'
Variables may be used almost anywhere that you use a literal value. Consider this series of statements:
$var1 = 'PHP'; // Assigns a value of 'PHP' to $var1
$var2 = 5; // Assigns a value of 5 to $var2
$var3 = $var2 + 1; // Assigns a value of 6 to $var3
$var2 = $var1; // Assigns a value of 'PHP' to $var2
echo $var1; // Outputs 'PHP'
echo $var2; // Outputs 'PHP'
echo $var3; // Outputs '6'
echo $var1 . ' rules!'; // Outputs 'PHP rules!'
echo "$var1 rules!"; // Outputs 'PHP rules!'
echo '$var1 rules!'; // Outputs '$var1 rules!'
Notice the last two lines in particular. You can include the name of a variable right inside a text string, and have the value inserted in its place if you surround the string with double quotes instead of single quotes. This process of converting variable names to their values is known as variable interpolation. However, as the last line demonstrates, a string surrounded with single quotes will not interpolate the variable names it contains.
Arrays
An array is a special kind of variable that contains multiple values. If you think of a variable as a box that contains a value, then an array can be thought of as a box with compartments, where each compartment is able to store an individual value.
The simplest way to create an array in PHP is to use the built-in array function:
$myarray = array('one', 2, '3');
This code creates an array called $myarray that contains three values: 'one', 2, and '3'. Just like an ordinary variable, each space in an array can contain any type of value. In this case, the first and third spaces contain strings, while the second contains a number.
To access a value stored in an array, you need to know its index. Typically, arrays use numbers, starting with zero, as indices to point to the values they contain. That is, the first value (or element) of an array has index 0, the second has index 1, the third has index 2, and so on. In general, therefore, the index of the nth element of an array is n–1. Once you know the index of the value you’re interested in, you can retrieve that value by placing that index in square brackets after the array variable name:
echo $myarray[0]; // Outputs 'one'
echo $myarray[1]; // Outputs '2'
echo $myarray[2]; // Outputs '3'
Each value stored in an array is called an element of that array. You can use an index in square brackets to add new elements, or assign new values to existing array elements:
$myarray[1] = 'two'; // Assign a new value
$myarray[3] = 'four'; // Create a new element
You can add elements to the end of an array using the assignment operator as usual, but leaving empty the square brackets that follow the variable name:
$myarray[] = 'the fifth element';
echo $myarray[4]; // Outputs 'the fifth element'
However, numbers are only the most common choice for array indices; there’s another possibility. You can also use strings as indices to create what’s called an associative array. This type of array is called associative because it associates values with meaningful indices. In this example, we associate a date (in the form of a string) with each of three names:
$birthdays['Kevin'] = '1978-04-12';
$birthdays['Stephanie'] = '1980-05-16';
$birthdays['David'] = '1983-09-09';
The array function also lets you create associative arrays, if you prefer that method. Here’s how we’d use it to create the $birthdays array:
$birthdays = array('Kevin' => '1978-04-12',
'Stephanie' => '1980-05-16', 'David' => '1983-09-09');
Now, if we want to know Kevin’s birthday, we look it up using the name as the index:
echo 'My birthday is: ' . $birthdays['Kevin'];
This type of array is especially important when it comes to user interaction in PHP, as we’ll see in the next section. I’ll demonstrate other uses of arrays throughout this book.
Kevin began developing for the Web in 1995 and is a highly respected technical author. He wrote