Up to this point, our web applications have involved two documentsan HTML opening page that gathers data from the user, and a PHP page that interprets and handles that data. However, many web applications that use PHP are written in a single PHP page. For example, say that you wanted to ask for the user's name and then display that name, all using the same PHP script. To wrap everything into one page, you'll need to be able to determine if this is the first time the user has seen the page, and if so, then you need to display the data-gathering page, sometimes called the welcome page. If the user has already entered his or her data, on the other hand, you need to read that data. This means you can determine what you're supposed to be doing by checking whether any data is ready for you to read. We'll use a text field named "Name" to hold the name of the user, so if it holds some data, we should display the name this way: <?php if(isset($_REQUEST["Name"])){ ?> <H1>Using Text Fields</H1> Your name is <?php echo $_REQUEST["Name"]; } On the other hand, if no data is waiting for you, you should display the text field and a prompt for the user to enter his or her name, as shown in phpsingle.php, Example 6-9. Example 6-9. Using one PHP document, phpsingle.php<HTML> <HEAD> <TITLE>Using Text Fields</TITLE> </HEAD> <BODY> <CENTER><H1>Using Text Fields</H1> <?php if(isset($_REQUEST["Name"])){ ?> <H1>Using Text Fields</H1> Your name is <?php echo $_REQUEST["Name"]; } else { ?> <FORM METHOD="POST" ACTION="phptext.php"> What's your name? <INPUT NAME="Name" TYPE="TEXT"> <BR><BR> <INPUT TYPE=SUBMIT VALUE=Submit> </FORM> <?php } ?> </CENTER> </BODY> </HTML> Note that we're setting the ACTION attribute to the name of the current script (that's actually unnecessary; if you omit the ACTION attribute, the form's data will be sent back to the current PHP document). You can see the results of all this in Figure 6-9, where the PHP script is displaying the welcome page. Figure 6-9. Putting everything into one PHP document.When you click Submit, the script displays the user's name, as shown in Figure 6-10. Figure 6-10. The results page.Being able to wrap everything into one page like this is very handy. |