Page 286 - Beginning PHP 5.3
P. 286
Part III: Using PHP in Practice
Now the function loops through the required field names and looks for each field name in the $_POST
array. If the field name doesn ’ t exist, or if it does exist but its value is empty, the field name is added to
the $missingFields array:
foreach ( $requiredFields as $requiredField ) {
if ( !isset( $_POST[$requiredField] ) or !$_POST[$requiredField] ) {
$missingFields[] = $requiredField;
}
}
If missing fields were found, the function calls the displayForm() function to redisplay the form,
passing in the array of missing field names so that displayForm() can highlight the appropriate fields.
Otherwise, displayThanks() is called to thank the user:
if ( $missingFields ) {
displayForm( $missingFields );
} else {
displayThanks();
}
}
The displayForm() function itself displays the HTML form to the user. It expects an array of any
missing required field names. If this array is empty, the form is presumably being displayed for the first
time, so displayForm() shows a welcome message. However, if there are elements in the array, the
form is being redisplayed because there were errors, so the function shows an appropriate error message:
function displayForm( $missingFields ) {
?>
<h1>Membership Form</h1>
<?php if ( $missingFields ) { ?>
<p class=”error”>There were some problems with the form you submitted.
Please complete the fields highlighted below and click Send Details to resend
the form.</p>
<?php } else { ?>
<p>Thanks for choosing to join The Widget Club. To register, please fill
in your details below and click Send Details. Fields marked with an asterisk
(*) are required.</p>
<?php } ?>
Next, the form itself is displayed. The form uses the post method, and its action attribute points back
to the script ’ s URL:
< form action=”registration.php” method=”post” >
Then each form control is created using HTML markup. Notice how the validateField() ,
setValue() , setChecked() , and setSelected() functions are called throughout the markup in order
to insert appropriate attributes into the elements.
With the password fields, it ’ s unwise to redisplay a user ’ s password in the page because the password
can easily be read by viewing the HTML source. Therefore, the two password fields are always
248
9/21/09 7:23:43 PM
c09.indd 248 9/21/09 7:23:43 PM
c09.indd 248