Build Your Own Database Driven Website Using PHP & MySQL: Pt. 3

Thursday Jan 17th 2002 by Kevin Yank
Share:

Part three of our 'Build Your Own Database Driven Website Using PHP & MySQL' series introduces PHP, variables and operators, user interaction and forms, control structures, and multi-purpose pages.

In Chapter 2, we learned how to use the MySQL database engine to store a list of jokes in a simple database (composed of a single table named "Jokes"). To do so, we used the MySQL command-line client to enter SQL commands (queries). In this chapter, we'll introduce the PHP server-side scripting language. In addition to the basic features we'll explore here, this language has full support for communication with MySQL databases.

As we've discussed previously, PHP is a server-side scripting language. This concept is not obvious, especially if you're used to designing pages with just HTML and JavaScript. A server-side scripting language is similar to JavaScript in many ways, as they both allow you to embed little programs (scripts) into the HTML of a Web page. When executed, such scripts allow you to control what will actually appear in the browser window with more flexibility than is possible using straight HTML.

The key difference between JavaScript and PHP is simple. JavaScript is interpreted by the Web browser once the Web page that contains the script has been downloaded. Meanwhile, server- side scripting languages like PHP are interpreted by the Web server before the page is even sent to the browser. And, once it's interpreted, the results of the script replace the PHP code in the Web page itself, so all the browser sees is a standard HTML file. The script is processed entirely by the server, hence the designation: server-side scripting language.

Let's look back at the today.php example presented in Chapter 1:

<html>
<head>
<title>Today's Date</title>
</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. The line between <?php and ?>, however, is written in PHP. <?php means "begin PHP code", and ?> means "end PHP code". 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 something like this:

<html>
<head>
<title>Today's Date</title>
</head>
<body>
<p>Today's Date (according to this Web server) is
Wednesday, May 30th 2001.</p>
</body>
</html>

Notice that all signs of the PHP code have disappeared. In their place, the output of the script has appeared, and 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 and nothing else, so you don't have to worry about whether the language you're using will be supported by your visitors' browsers.
  • 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 would only be able to display the date according to the computer on which the Web browser was running. Now, while this isn't an especially impressive example of the exploitation of server-side resources, we could just as easily have inserted some other information that would only be available to a script running on the Web server, for example, information stored in a MySQL database that runs on the Web server computer.
  • Reduced load on the client. JavaScript can significantly slow down the display of a Web page on slower computers, as the browser must run the script before it can display the Web page. With server-side scripting, this becomes the burden of the Web server machine.

Basic Syntax and Commands

PHP syntax will be very familiar to anyone with an understanding of C, C++, Java, JavaScript, Perl, or any other C- derived language. A PHP script consists of a series of commands, or statements, each of which is an instruction that the Web server must follow 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 <b>test</b>!" );

This statement invokes a built-in function called echo and passes it a string of text: This is a <b>test</b>! Built-in functions can be thought of as things that PHP knows how to do without us having to spell out the details. PHP has a lot of built-in functions that let us do everything from sending email, to working with information that's stored in various types of databases. The echo function, however, simply takes the text that it's given, and places it into the HTML code of the page at the current location. Consider the following (echo.php in the code archive):

<html>
<head>
<title> Simple PHP Example </title>
</head>
<body>
<p><?php echo("This is a <b>test</b>!"); ?></p>
</body>
</html>

If you paste this code into a file called echo.php (or echo.php3, if your Web host has not configured .php files to be recognized as PHP scripts) and place it on your Web server, a browser that views the page will see this:

<html>
<head>
<title> Simple PHP Example </title>
</head>
<body>
<p>This is a <b>test</b>!</p>
</body>
</html>

Notice that the string of text contained HTML tags (<b> and </b>), which is perfectly acceptable.

You may wonder why we need to surround the string of text with both parentheses and quotes. Quotes are used to mark the beginning and end of strings of text in PHP, so their presence is fully justified. The parentheses serve a dual purpose. First, they indicate that echo is a function that you want to call. Second, they mark the beginning and end of a list of "parameters" that you wish to provide, in order to tell the function what to do. In the case of the echo function, you only need to provide the string of text that you want to appear on the page. Later on, we'll look at functions that take more than one parameter (and we'll separate those parameters with commas), and we'll consider functions that take no parameters at all (for which we'll still need the parentheses, though we won't type anything between them).

Variables in PHP are identical to variables in most other programming languages. For the uninitiated, a variable is a name given to an imaginary box into which any 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 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 it appears after the statement above, assigns a new value to our 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 is 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.

The lines above each end with a comment. Comments are a way to describe what your code is doing - they insert explanatory text into your code, and tell the PHP interpreter to ignore it. Comments begin with // and they finish at the end of the same line. You might be familiar with /* */ style comments in other languages - these work in PHP as well. I'll be using comments throughout the rest of this series to help explain what the code I present is doing.

Now, to get back to the four statements above, the operators we used here allow you to add, subtract, multiply, and divide numbers. Among others, there is also an operator that sticks strings of text together, called the concatenation operator:

$testvariable = "Hi " . "there!"; // Assigns a value of "Hi there!".

Variables may be used almost anywhere that you use an actual value. Consider these examples:

$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 especially. 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. This process of converting variable names to their values is known in technical circles as variable interpolation. However, as the last line demonstrates, a string surrounded with single quotes will not interpolate variable names within the string.

For many applications of PHP, the ability to interact with users who view the Web page is essential. Veterans of JavaScript tend to think in terms of event handlers, which let you react directly to the actions of the user - for example, the movement of the mouse over a link on the page. Server-side scripting languages such as PHP have a more limited scope when it comes to user interaction. As PHP code is activated when a page is requested from the server, user interaction can only occur in a back-and- forth fashion: the user sends requests to the server, and the server replies with dynamically generated pages.

The key to creating interactivity with PHP is to understand the techniques we can use to send information about a users' interaction along with their request for a new Web page. PHP makes this fairly easy, as we'll now see.

The simplest method we can use to send information along with a page request uses the URL query string. If you've ever seen a URL with a question mark following the filename, you've witnessed this technique in use. Let's look at an easy example. Create a regular HTML file called welcome.html (no .php file extension is required, since there will be no PHP code in this file) and insert this link:

<a href="welcome.php?name=Kevin"> Hi, I'm Kevin! </a>

This is a link to a file called welcome.php, but as well as linking to the file, we're also passing a variable along with the page request. The variable is passed as part of the "query string", which is the portion of the URL that follows the question mark. The variable is called name and its value is Kevin. To restate, we have created a link that loads welcome.php, and informs the PHP code contained in the file that name equals Kevin.

To really understand the results of this, we need to look at welcome.php. Create it as a new HTML file, but this time note the .php extension -- this tells the Web server that it can expect to interpret some PHP code in the file. If your Web server is not configured to accept .php as a file extension for PHP files, you may have to call it welcome.php3 instead (in which case you'll also want to adjust the link above accordingly). In the body of this new file, type:

<?php
  echo( "Welcome to our Web site, $name!" );
?>

Now, if you use the link in the first file to load this second file, you'll see that the page says "Welcome to our Web site, Kevin!" The value of the variable passed in the query string of the URL was automatically placed into a PHP variable called $name, which we used to display the value passed as part of a text string.

You can pass more than one value in the query string if you want to. Let's look at a slightly more complex version of the same example. Change the link in the HTML file to read as follows (this is welcome2.html in the code archive):

<a href="welcome.php?firstname=Kevin&lastname=Yank">
Hi, I'm Kevin Yank! </a>

This time, we'll pass two variables: firstname and lastname. The variables are separated in the query string by an ampersand (&). You can pass even more variables by separating each name=value pair from the next with an ampersand.

As before, we can use the two variable values in our welcome.php file (this is welcome2.php in the code archive):

<?php
  echo( "Welcome to our Web site, $firstname $lastname!" );
?>

This is all well and good, but we still have yet to achieve our goal of true user interaction, where the user can actually enter arbitrary information and have it processed by PHP. To continue with our example of a personalized welcome message, we'd like to allow the user to actually type his or her name and have it appear in the message. To allow the user to type in a value, we'll need to use an HTML form.

Here's the code (welcome3.html):

<form action="welcome.php" method="get">
First Name: <input type="text" name="firstname" /><br />
Last Name: <input type="text" name="lastname" /><br />
<input type="submit" value="GO" />
</form>

Don't be alarmed at the slashes that appear in some of these tags (e.g. <br />). The new XHTML standard for coding Web pages, calls for these in any tag that does not have a closing tag, which includes <input> and <br> tags, among others. Current browsers do not require you to use the slashes, of course, but for the sake of standards-compliance, the HTML code in this series will observe this recommendation. Feel free to leave the slashes out if you prefer (I agree that they're not especially nice to look at).

This form has the exact same effect as the second link we looked at (with firstname=Kevin&lastname=Yank in the query string), except that you can enter whatever names you like. When you click the submit button (which has a label of "GO"), the browser will load welcome.php and automatically add the variables and their values to the query string for you. It retrieves the names of the variables from the name attributes of the input type="text" tags, and it obtains the values from the information the user typed into the text fields.

The method attribute of the form tag is used to tell the browser how to send the variables and their values along with the request. A value of get (as used above) causes them to be passed in the query string, but there is an alternative. It's not always desirable -- or even technically feasible -- to have the values appear in the query string. What if we included a <textarea> tag in the form, to let the user enter a large amount of text? A URL that contained several paragraphs of text in the query string would be ridiculously long, and would exceed by far the maximum length of the URL in today's browsers. The alternative is for the browser to pass the information invisibly, behind the scenes. The code for this looks exactly the same, but where we set the form method to get in the last example, here we set it to post (welcome4.html):

<form action="welcome.php" method="post">
First Name: <input type="text" name="firstname" /><br />
Last Name: <input type="text" name="lastname" /><br />
<input type="submit" value="GO" />
</form>

This form is functionally identical to the previous one. The only difference is that the URL of the page that's loaded when the user clicks the "GO" button will not have a query string. On the one hand, this lets you include large values, or sensitive values (like passwords) in the data that's submitted by the form, without their appearing in the query string. On the other hand, if the user bookmarks the page that results from their submission of the form, that bookmark will be useless, as it doesn't contain the submitted values. This, incidentally, is the main reason that search engines like AltaVista use the query string to submit search terms. If you bookmark a search results page on AltaVista, you can use that bookmark to perform the same search again later, because the search terms are contained in the URL.

That covers the basics of using forms to produce rudimentary user interaction with PHP. We'll cover more advanced issues and techniques in later examples.

All the examples of PHP code that we've seen so far have been either simple, one-statement scripts that output a string of text to the Web page, or have been series of statements that were to be executed one after the other in order. If you've ever written programs in any other languages (be they JavaScript, C, or BASIC) you already know that practical programs are rarely so simple.

PHP, just like any other programming language, provides facilities that allow us to affect the flow of control in a script. That is, the language contains special statements that permit you to deviate from the one-after-another execution order that has dominated our examples so far. Such statements are called control structures. Don't get it? Don't worry! A few examples will illustrate perfectly.

The most basic, and most often-used, control structure is the if-else statement. Here's what it looks like:

if ( condition ) {
  // Statement(s) to be executed if
  // condition is true.
} else {
  // (Optional) Statement(s) to be
  // executed if condition is false.
}

This control structure lets us tell PHP to execute one set of statements or another, depending on whether some condition is true or false. If you'll indulge my vanity for a moment, here's an example that shows a twist on the welcome.php file we created earlier:

if ( $name == "Kevin" ) {
  echo( "Welcome, oh glorious leader!" );
} else {
  echo( "Welcome, $name!" );
}

Now, if the name variable passed to the page has a value of Kevin, a special message will be displayed. Otherwise, the normal message will be displayed and will contain the name that the user entered.

As indicated in the code structure above, the else clause (that part of the if-else statement that says what to do if the condition is false) is optional. Let's say you wanted to display the special message above only if the appropriate name was entered, but otherwise, you didn't want to display any message. Here's how the code would look:

if ( $name == "Kevin" ) {
  echo( "Welcome, oh glorious leader!" );
}

The == used in the condition above is the PHP operator that's used to compare two values to see whether they're equal. It's important to remember to type the double-equals, because if you were to use a single equals sign you'd be using the assignment operator discussed above. So, instead of comparing the variable to the designated value, you'd assign a new value to the variable (an operation which, incidentally, evaluates as true). This would not only cause the condition to always be true, but might change the value in the variable you're checking, which could cause all sorts of problems.

Conditions can be more complex than a single comparison for equality. Recall that we modified welcome.php to take a first and last name. If we wanted to display a special message only for a particular person, we'd have to check the values of both names (welcome3.php):

if ( "Kevin" == $firstname and "Yank" == $lastname ) {
  echo( "Welcome, oh glorious leader!" );
} else {
  echo( "Welcome to our Web site, $firstname $lastname!" );
}

This condition will be true if and only if $firstname has a value of Kevin and $lastname has a value of Yank. The word and in the above condition makes the whole condition true only if both of the comparisons evaluate to true. Another such operator is or, which makes the whole condition true if one or both of two simple conditions are true. If you're more familiar with the JavaScript or C forms of these operators (&& and || for and and or respectively), they work in PHP as well.

We'll look at more complicated comparisons as the need arises. For the time being, a general familiarity with the if- else statement is sufficient.

Another often-used PHP control structure is the while loop. Where the if-else statement allowed us to choose whether or not to execute a set of statements depending on some condition, the while loop allows us to use a condition to determine how many times to repeatedly execute a set of statements. Here's what a while loop looks like:

while ( condition ) {
  // statement(s) to execute over
  // and over as long as condition
  // remains true
}

This works very similarly to an if-else statement without an else clause. The difference arises when the condition is true and the statement(s) are executed. Instead of continuing the execution with the statement that follows the closing brace (}), the condition is checked again. If the condition is still true, then the statement(s) are executed a second time, and a third, and will continue to be executed as long as the condition remains true. The first time the condition evaluates false (whether it's the first time it's checked or the one-hundred-and-first), execution jumps immediately to the next statement that follows the while loop (after the closing brace).

Loops like these come in handy whenever you're working with long lists of things (such as jokes stored in a database... hint- hint!), but for now we'll illustrate with a trivial example: counting to ten. This script is available as count10.php in the code archive.

$count = 1;
while ($count <= 10) {
  echo( "$count " );
  $count++;
}

It looks kind of scary, I know, but let me talk you through it line by line. The first line creates a variable called $count and assigns it a value of 1. The second line is the start of a while loop, the condition for which is that the value of $count is less than or equal (<=) to 10. The third and fourth lines make up the body of the while loop, and will be executed over and over, as long as that condition holds true. The third line simply outputs the value of $count followed by a space. The fourth line adds one to the value of $count ($count++ is a shortcut for $count = $count + 1 -- both will work).

So here's what happens when this piece of code is executed. The first time the condition is checked, the value of $count is 1, so the condition is definitely true. The value of $count (1) is output, and $count is given a new value of 2. The condition is still true the second time it is checked, so the value (2) is output and a new value (3) is assigned. This process continues, outputting the values 3, 4, 5, 6, 7, 8, 9, and 10. Finally, $count is given a value of 11, and the condition is false, which ends the loop. The net result of the code is to output the string "1 2 3 4 5 6 7 8 9 10 ".

The condition in this example used a new operator: <= (less than or equal). Other numerical comparison operators of this type include >= (greater than or equal), < (less than), > (greater than), and != (not equal). That last one also works when comparing text strings, by the way.

Let's say you wanted to construct your site so that it showed the visitor's name at the top of every page. With our custom welcome message example above, we're halfway there already. Here are the problems we'll need to overcome to extend the example into what we need:

  • We need the name on every page of the site, not just one.
  • We have no control over which page of our site users will view first.

The first problem isn't too hard to overcome. Once we have the user's name in a variable on one page, we can pass it with any request to another page by adding the name to the query string of all links:


<a href="newpage.php?name=<?php echo(urlencode($name)); ?>"> A link </a>

Notice that we've embedded PHP code right in the middle of an HTML tag. This is perfectly legal, and will work just fine. A shortcut exists for those times when you simply want to echo a PHP value in the middle of your HTML code. The shortcut looks like this:

<a href="newpage.php?name=<?=urlencode($name)?>"> A link </a>

The tags <?= ... ?> perform the same function as the much longer code <?php echo( ... ); ?>. This is a handy shortcut that I'll use several times through the rest of this series.

You're familiar with the echo function, but urlencode is probably new to you. This function takes any special characters in the string (for example, spaces) and converts them into the special codes they need to be in order to appear in the query string. For example, if the $name variable had a value of "Kevin Yank", then as spaces are not allowed in the query string, the output of urlencode (and thus the string output by echo) would be "Kevin+Yank". This would then be automatically converted back by PHP when it created the $name variable in newpage.php.

Okay, so we've got the user's name being passed with every link in our site. Now all we need is to get that name in the first place. In our welcome message example, we had a special HTML page with a form in it that prompted the user for his or her name. The problem with this (identified by the second point above) is that we couldn't — nor would we wish to — force the user to enter our Web site by that page every time he or she visited our site.

The solution is to have every page of our site check to see if a name has been specified, and prompt the user for a name if necessary. This means that every page of our site will either display its content, or a prompt the user to enter a name, depending on whether the $name variable is found to have a value. If this is beginning to sound to you like a good place for an if-else statement, you're a quick study!

We'll refer to pages that are capable of displaying completely different content depending on some condition, as "multi-purpose pages". The code of a multi-purpose page looks something like this:

<html>
<head>
<title> Multi-Purpose Page Outline </title>
</head>
<body>

<?php if (condition) { ?>
<!-- HTML content to display if condition is true -->
<?php } else { ?>
<!-- HTML content to display if condition is false -->
<?php } ?>

</body>
</html>

This may confuse you at first, but in fact this is just a normal if-else statement with HTML code sections that depend on the condition, instead of PHP statements. This example illustrates one of the big selling points of PHP: that you can switch in and out of "PHP mode" whenever you like. If you think of <?php as the command to switch into "PHP mode", and ?> as the command to go back into "normal HTML mode", the above example should make perfect sense.

There's an alternate form of the if-else statement that can make your code more readable in situations like this. Here's the outline for a multi-purpose page using the alternate if-else form:

<html>
<head>
<title> Multi-Purpose Page Outline </title>
</head>
<body>

<?php if (condition): ?>
<!-- HTML content to display if condition is true -->
<?php else: ?>
<!-- HTML content to display if condition is false -->
<?php endif; ?>

</body>
</html>

Okay, now that we have all the tools we need in hand, let's look at a sample page of our site (samplepage.php in the code archive):

<html>
<head>
<title> Sample Page </title>
</head>
<body>

<?php if ( !isset($name) ): ?>
  <!-- No name has been provided, so we
       prompt the user for one.         -->
  <form action="<?=$PHP_SELF?>" method="get">
  Please enter your name: <input type="text" name="name" />
  <input type="submit" value="GO" />
  </form>
<?php else: ?>
  <p>Your name: <?=$name?></p>
  <p>This paragraph contains a
  <a href="newpage.php?name=<?=urlencode($name)?>">link</a>
  that passes the name variable on to the next document.</p>
<?php endif; ?>

</body>
</html>

There are two new tricks in the above code, but overall you should be pretty comfortable with the way it works. First of all, we're using a new function called isset in the condition. This function returns (outputs) a value of true if the variable it is given has been assigned a value (i.e. if a name has been provided), and false if the variable does not exist (i.e. if a name has not yet been given). The exclamation mark (also known as the negation operator, or the not operator) that appears before the name of the function reverses the returned value from true to false or vice-versa. Thus, the form is displayed when the $name variable is not set. The second new trick is the use of the variable $PHP_SELF to specify the action attribute of the form tag. This variable is one of several that PHP always gives a value to automatically. In particular, $PHP_SELF will always be set to the URL of the current page. This gives us an easy way to create a form that, when submitted, will load the very same page, but this time with the $name variable specified.

If we structure all the pages on our site in this way, visitors will be prompted for their name by the first page they attempt to view, whichever page this happens to be. Once they enter their name and click "GO", they'll be presented with the exact page they requested. The name they entered is then passed in the query string of every link from that point onward, ensuring that they are prompted only the once.

Summary

In this chapter, we've had a taste of the PHP server-side scripting language by exploring all the basic language features: statements, variables, operators, and control structures. The sample applications we've seen have been pretty simple, but don't let that dissuade you. The real power of PHP is in the hundreds of built-in functions that let you do everything: access data in a MySQL database, send e-mail, dynamically generate images, and even create Adobe Acrobat PDF files on the fly.

Share:
Home
Mobile Site | Full Site
Copyright 2017 © QuinStreet Inc. All Rights Reserved