| PHP - Intelligent Form Handling |
PHP - Intelligent Form Handling
Here is a slightly more complex example. We are going to create an HTML form that asks the user to enter a name and select one or more interests from a selection box. We could do this in two files, where we separate the actual form from the data handling code, but instead, this example shows how it can be done in a single file:
There are a few things to study carefully in this example. First, we have isolated the display of the actual form to a PHP function called show_form(). This function is intelligent, in that it can take the default value for each of the form elements as an optional argument. If the user does not fill in all the form elements, we use this feature to redisplay the form with whatever values the user has already entered. This means the user only has to fill the fields he missed, which is much better than asking the user to hit the Back button or forcing him to reenter all the fields.
Notice how the file switches back and forth between PHP code and HTML. Right in the middle of defining our show_form() function, we switch back to HTML to avoid having numerous echo statements that just echo normal HTML. Then, when we need a PHP variable, we switch back to PHP code temporarily, just to print the variable.
We've given the multiple-choice <select> element the name interest[ ]. The [ ] on the name tells PHP that the data coming from this form element should be treated as an auto-indexed array. This means that PHP automatically gives each element the next sequential index, starting with 0 (assuming the array is empty to begin with).
The final thing to note is the way we determine what to display. We check if the SERVER variable REQUEST_METHOD is set to POST. If it isn't, we know that the user has not submitted the form yet, so we call show_form() without any arguments. This displays the empty form. If $first is set, however, we check to make sure that the $first and $last text fields are not empty and that the user has selected at least one interest.
| Users' Comments (0) |
|
No comment posted








