Handling HTML Forms with PHP Redux

All of the examples in this chapter and the previous one used two separate scripts for handling HTML forms: one that displayed the form and another that received it. While there’s certainly nothing wrong with this method, there are advantages to having the entire process in one script. To have one page both display and handle a form, use a conditional.

if (/* form has been submitted */) {
   // Handle it.
} else {
   // Display it.

To determine if the form has been submitted, I normally check if the $submit variable is set (which is the name of the submit input type in the form).

if (isset($_POST['submit'])) {
   // Handle it.
} else {
   // Display it.
   echo '<input type="submit" name="submit" value="Go!">';
}

If you ...

Get PHP and MySQL for Dynamic Web Sites: Visual QuickPro Guide 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.