Creating a Simple Input Form

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

Listing 11.1. A Simple HTML Form

  1: <html>  2: <head>  3: <title>A simple HTML form</title>  4: </head>  5: <body>  6: <form action="send_simpleform.php" method="POST">  7: <p><strong>Name:</strong><br/>  8. <input type="text" name="user"/></p>  9: <p><strong>Message:</strong><br/> 10: <textarea name="message" rows="5" cols="40"></textarea></p> 11: <p><input type="submit" value="send"/></p> 12: </form> 13: </body> 14: </html>

Put these lines into a text file called simpleform.html 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 "message" on line 10, and a submit button on line 11. The FORM element's ACTION argument points to a file called send_simpleform.php, which processes the form information. The method of this form is POST, so the variables are stored in the $_POST superglobal.

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

Listing 11.2. Reading Input from a Form

 1: <?php 2: echo "<p>Welcome <b>".$_POST["user"]."</b>!</p>"; 3: echo "<p>Your message is:<br/><b>".$_POST["message"]."</b></p>"; 4: ?>

Put these lines into a text file called send_simpleform.php and place that file in your web server document root. Now access the form itself (simpleform.html) with your web browser, and you should see something like Figure 11.1.

Figure 11.1. The form created by simpleform.html.

The script in Listing 11.2 is called when the user submits the form created in Listing 11.1. In the code in Listing 11.2, we access two variables: $_POST["user"] and $_POST["message"]. These are references to the variables in the $_POST superglobal, which contain the values that the user entered in the user text field and the message text area. Forms in PHP really are as simple as that.

Enter some information in the form fields and click the send button. You should see your input echoed to the screen.

By the Way

You could also use the GET method in this form (and others). POST can handle more data than GET and does not pass the data in the query string. If you use the GET method, be sure to change your superglobal to $_GET and not $_POST.

Sams Teach Yourself PHP, MySQL And Apache All in One
Sams Teach Yourself PHP, MySQL and Apache All in One (3rd Edition)
ISBN: 0672328739
EAN: 2147483647
Year: 2004
Pages: 327

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: