Retrieving Data from Text Fields


In the previous chunk, we created a web page with an HTML text field in a form that will send the contents of the text field to phptext.php when the user clicks the Submit button. So how can you retrieve the data from that text field?

We'll embed the user's name in a web page starting with the text "Your name is":

 <HTML>     <HEAD>         <TITLE>             Using Text Fields         </TITLE>     </HEAD>     <BODY>         <CENTER>             <H1>                 Retrieving Data From Text Fields             </H1>             Your name is             .             .             .         </CENTER>     </BODY> </HTML> 

To retrieve data from the web page, we'll use the $_REQUEST array, which holds the combined data of the $_POST and $_GET arrays, which means that you can use $_REQUEST with web pages that send you data using either the GET or POST methods. In the HTML page, phptext.html, we named the text field "Name" with the HTML NAME attribute, so to recover the value in that text field in the PHP script, you just use $_REQUEST["Name"], as shown in phptext.php, Example 5-2.

Example 5-2. Reading data from a text field, phptext.php
 <HTML>     <HEAD>         <TITLE>             Using Text Fields         </TITLE>     </HEAD>     <BODY>         <CENTER>             <H1>                 Retrieving Data From Text Fields             </H1>             Your name is             <?php                  echo $_REQUEST["Name"];             ?>         </CENTER>     </BODY> </HTML> 

That's all it takes; now we're able to read the data the user entered into a text field. You can see the results in Figure 5-2, where we've gotten the user's name and displayed it. Now we're interacting with and accepting input from the user. Very cool.

Figure 5-2. Reading data from a text field.


That's how it works in PHPyou recover data from HTML controls like this: $_REQUEST["ControlName"], which will handle both GET and POST requests. If you prefer, you can use the $_GET or $_POST arrays instead; for example, if you've used the POST method:

 <FORM METHOD="POST" ACTION="phptext.php">     What's your name?     <INPUT NAME="Name" TYPE="TEXT">     <BR>     <BR>     <INPUT TYPE="SUBMIT" VALUE="Submit"> </FORM> 

Then you could use $_POST to recover data with:

 Your name is <?php     echo $_POST["Name"]; ?> 



    Spring Into PHP 5
    Spring Into PHP 5
    ISBN: 0131498622
    EAN: 2147483647
    Year: 2006
    Pages: 254

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net