Combining a Form and Its Results

Combining a Form and Its Results

Most of your PHP programs up to now have had two distinct files. An HTML file has a form, which calls a PHP program. Sometimes it can be tedious to keep track of two separate files. You can use the if statement to combine both functions into one page. The hiUser program shown in Figures 3.10 and 3.11 looks much like its counterpart in Chapter 2, Using Variables and Input, but it has an important difference. Rather than being an HTML page and a separate PHP program, the entire program resides in one file on the server.

Click To expand
Figure 3.10: The HTML page is actually produced through PHP code.
Click To expand
Figure 3.11: The result is produced by exactly the same program.

The code for the new version of hiUser shows how to achieve this trick.

<title>Hi User</title>
<h1>Hi User</h1>


if (empty($userName)){
  print <<<HERE
  Please enter your name:
  <input type = "text"
         name = "userName"><br>
  <input type = "submit">

} else {
  print "<h3>Hi there, $userName!</h3>";
} //end


This program begins by looking for the existence of a variable called $userName. The first time the program is called, there will be no $userName variable, because the program was not called from a form. The empty() function returns the value true if the specified variable is empty or false if it has a value. If $userName does not exist, empty($userName) will evaluate as true. The condition (empty($userName)) will generally be true if this is the first time this page has been called. If it's true, the program should generate a form so the user can enter his or her name. If the condition is false, that means somehow the user has entered a name (presumably through the form) so the program greets the user using that name.

The key idea here is that the program runs more than once. When the user first links to hiUser.php, the program creates a form. The user enters a value on the form, and presses the Submit button. This causes exactly the same program to be run again on the server. This time, though, the $userName variable is not empty, so rather than generating a form, the program uses the variable's value in a greeting.

Server-side programming frequently works in this way. It isn't uncommon for a user to call the same program many times in succession as part of solving a particular problem. You'll often use branching structures such as the if and switch statements to direct the flow of the program based on the user's current state of activity.