Getting Started with PHP - Control Structure, Multipurpose Pages

Started by sivaji, Jan 11, 2008, 03:01 PM

Previous topic - Next topic

sivaji

Getting Started with PHP

Control Structures

All the examples of PHP code we've seen so far have been either simple, onestatement scripts that output a string of text to the Web page, or series of statements that were to be executed one after the other in order. If you've ever written programs in other languages (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 personalized welcome page example we created earlier:

File: welcome6.php (excerpt)
$name = $_REQUEST['name'];
if ($name == 'Kevin') {
echo 'Welcome, oh glorious leader!';
} else {
echo "Welcome to our Website, $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. The result in the former case.

As indicated in the code structure above, the else clause (that part of the ifelse 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; otherwise, you didn't want to display any message. Here's how the code would look:

$name = $_REQUEST['name'];
if ($name == 'Kevin') {
echo 'Welcome, oh glorious leader!';
}

The == used in the condition above is the PHP equal-to operator that's used to compare two values to see whether they're equal.

Conditions can be more complex than a single comparison for equality. Recall that our form examples above would receive 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:

File: welcome7.php (excerpt)
$firstname = $_REQUEST['firstname'];
$lastname = $_REQUEST['lastname'];
if ($firstname == 'Kevin' and $lastname == 'Yank') {
echo 'Welcome, oh glorious leader!';
} else {
echo "Welcome to my Website, $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), that's fine—they work in PHP as well.

We'll look at more complicated conditions 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 we'll execute a set of statements repeatedly. Here's what a while loop looks like:

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

The while loop 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-andfirst), execution jumps immediately to the 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.

File: count10.php (excerpt)
$count = 1;
while ($count <= 10) {
echo "$count ";
++$count;
}

It looks a bit frightening, 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 short cut 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

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.

Another type of loop that is designed specifically to handle examples like that above, in which we're counting through a series of values until some condition is met, is called a for loop. Here's what it looks like:

for (initialize; condition; update) {
// statement(s) to execute over
// and over as long as condition
// remains true after each update
}

The initialize statement is executed once at the start of the loop; the condition statement is checked each time through the loop, before the statements in the body are executed; the update statement is executed each time through the loop, but after the statements in the body.

Here's what the "counting to 10" example looks like when implemented with a for loop:

File: count10–for.php (excerpt)
for ($count = 1; $count <= 10; ++$count) {
echo "$count ";
}

As you can see, the statements that initialize and increment the $count variable join the condition on the first line of the for loop. Although, at first glance, the code seems a little more difficult to read, putting all the code that deals with controlling the loop in the same place actually makes it easier to understand once you're used to the syntax. Many of the examples in this book will use for loops, so you'll have plenty of opportunity to practice reading them.

Multipurpose Pages

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:

         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($_GET['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.

You're familiar with echo statements, but the urlencode function is probably new to you. This function takes 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'. PHP would then convert it back automatically when it created the $_GET variable in newpage.php. Okay, so the user's name will be 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 containing a form 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 Website 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 prompt the user to enter a name, depending on whether the $name variable is found to have a value. If you think this is beginning to sound like a good place for an if-else statement, you're a quick study!

We'll refer to pages that can decide whether to display one thing or another as multipurpose pages. The code of a multipurpose page looks something like this:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

If this sounds like a lot of work to you, it is. Don't worry; we'll learn much more practical methods
for sharing variables between pages in Chapter 11. Again, if you're dreading the thought of adding PHP code to prompt the user for a name to every page of your site, don't fret; we'll cover a more practical way to do this later.

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Multipurpose Page Outline</title>
<meta http-equiv="content-type"
content="text/html; charset=iso-8859-1" />
</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 code 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 multipurpose page using the alternate if-else form:

<!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">
<head>
<title>Multipurpose Page Outline</title>
<meta http-equiv="content-type"
content="text/html; charset=iso-8859-1" />
</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:

File: samplepage.php

<!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">
<head>
<title>Sample Page</title>
<meta http-equiv="content-type"
content="text/html; charset=iso-8859-1" />
</head>
<body>
<?php if (!isset($_GET['name'])): ?>
<!-- No name has been provided, so we
prompt the user for one. -->
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="get">
<label>Please enter your name:
<input type="text" name="name" /></label>
<input type="submit" value="GO" />
</form>
<?php else: ?>
<p>Your name: <?php echo $_GET['name']; ?></p>
<p>This paragraph contains a
<a href="newpage.php?name=<?php echo urlencode($_GET['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 fairly 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 in this example), and false if the variable does not exist (i.e. if a name has not yet been provided). The exclamation mark (also known as the negation operator, or the not operator), which 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 $_GET['name'] variable is not set. The second new trick is the use of the variable $_SERVER['PHP_SELF'] to specify the action attribute of the <form> tag. Like $_GET, $_POST, and $_REQUEST, $_SERVER is an array variable that is automatically created by PHP. $_SERVER
contains a whole bunch of information supplied by your Web server. In particular, $_SERVER['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, as shown in Figure 3.8. Once they enter their names and click GO, they'll be presented with the exact page they requested. As shown in the status bar of the entered name is then passed in the query string of every link from that point onward, ensuring that the user is prompted only once.
Am now @ Chennai