Building Forms

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:

  • An opening <form> and closing </form> tag

  • A submission type specifying either a GET or POST method

  • One or more input fields

  • The destination URL to which the form data is to be submitted

Example 11-1 shows a very simple form created using PHP. Type it in and save it as formtest.php.

Example 11-1. formtest.php—a simple PHP form handler
<?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 ...

Get Learning PHP, MySQL, JavaScript, and CSS, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.