Handling forms is a multipart process. First a form is created, into which a user can enter the required details. This data is then sent to the web server, where it is interpreted, often with some error checking. If the PHP code identifies one or more fields that require reentering, the form may be redisplayed with an error message. When the code is satisfied with the accuracy of the input, it takes some action that usually involves the database, such as entering details about a purchase.
To build a form, you must have at least the following elements:
Example 11-1 shows a very simple form created using PHP. Type it in and save it as formtest.php.
<?php // formtest.php echo <<<_END <html> <head> <title>Form Test</title> </head> <body> <form method="post" action="formtest.php"> What is your name? <input type="text" name="name" /> <input type="submit" /> </form> </body> </html> _END; ?>
The first thing to notice about this example is that, as you have
already seen in this book, rather than dropping in and out of PHP code, I
generally use the echo
<<<_END..._END
heredoc construct when multiline HTML
must be output.
Inside this multiline output is some standard code for commencing an
HTML document, displaying its title, and starting the body of the
document. This is followed by the form, which is set to send its data
using the POST
method to the PHP
program formtest.php, which is the
name of the program itself.
The rest of the program just closes all the items it opened: the
form, the body of the HTML document, and the PHP echo <<<_END
statement. The result of
opening this program in a web browser can be seen in Figure 11-1.