Creating a Simple Input Form

For now, let's keep our HTML separate from our PHP code. Listing 9.2 builds a simple HTML form.

Listing 9.2 A Simple HTML Form
   1: <html>   2: <head>   3: <title>Listing 9.2 A simple HTML form</title>   4: </head>   5: <body>   6: <form action="listing9.3.php" method="POST">   7: Name: <br>   8: <input type="text" name="user">   9: <br>  10: Address: <br>  11: <textarea name="address" rows="5" cols="40"></textarea>  12: <br>  13: <input type="submit" value="hit it!">  14: </form>  15: </body>  16: </html> 

Put these lines into a text file called listing9.2.php, and place that file in your Web server document root. This listing defines a form that contains a text field with the name "user" on line 8, a text area with the name "address" on line 11, and a submit button on line 13. The FORM element's ACTION argument points to a file called listing9.3.php, which processes the form information. The method of this form is POST, so the variables are stored in the $_POST superglobal.

Listing 9.3 creates the code that receives our users' input.

Listing 9.3 Reading Input from the Form in Listing 9.2
   1: <html>   2: <head>   3: <title>Listing 9.3 Reading input from the form in Listing 9.2</title>   4: </head>   5: <body>   6: <?php   7: print "Welcome <b>$_POST[user]</b><P>\n\n";   8: print "Your address is:<P>\n\n<b>$_POST[address]</b>";   9: ?>  10: </body>  11: </html> 

Put these lines into a text file called listing9.3.php, and place that file in your Web server document root. Now access the form itself with your Web browser, and you should see something like Figure 9.2.

Figure 9.2. Form created in Listing 9.2.

graphics/09fig02.gif

The script in Listing 9.3 is the first script in this book that isn't designed to be called by clicking a link or typing directly into the browser's location field. Instead, this file is called when a user submits the form defined in Listing 9.2.

In the code, we access two variables: $_POST[user] and $_POST[address]. These are references to the variables in the $_POST superglobal, which contain the values that the user added to the "user" text field and the "address" text area. Forms in PHP really are as simple as that.

Enter some information in the form fields, and click the Hit It! button. You should see your input echoed to the screen.



Sams Teach Yourself PHP, MySQL and Apache in 24 Hours
Sams Teach Yourself PHP, MySQL and Apache in 24 Hours
ISBN: 067232489X
EAN: 2147483647
Year: 2005
Pages: 263

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