Handling HTML Forms with PHP Redux

All of the examples in this chapter and the preceding 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 that a $_POST variable is set (assuming that the form uses the POST method, of course). For example, you can check $_POST['submitted'], assuming that’s the name of a hidden input type in the form.

if (isset($_POST['submitted'])) ...

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