Page 279 - Beginning PHP 5.3
P. 279
Chapter 9: Handling HTML Forms with PHP
The square brackets tell the PHP engine to expect multiple values for these fields, and to create
corresponding nested arrays within the relevant superglobal arrays ($_POST and $_REQUEST in this case).
The form handler, process_registration_multi.php, displays the user’s submitted form data in the
page. Because most fields contain just one value, it’s simply a case of displaying the relevant $_POST
values using the echo() statement.
For the multi-value fields, however, the script needs to be a bit smarter. First it creates two empty string
variables to hold the list of field values to display:
$favoriteWidgets = “”;
$newsletters = “”;
Next, for the favoriteWidgets field, the script checks to see if the corresponding $_POST array element
($_POST[“favoriteWidgets”]) exists. (Remember that, for certain unselected form controls such as
multi-select lists and checkboxes, PHP doesn’t create a corresponding $_POST/$_GET/$_REQUEST array
element.) If the $_POST[“favoriteWidgets”] array element does exist, the script loops through each
of the array elements in the nested array, concatenating their values onto the end of the
$favoriteWidgets string, along with a comma and space to separate the values:
if ( isset( $_POST[“favoriteWidgets”] ) ) {
foreach ( $_POST[“favoriteWidgets”] as $widget ) {
$favoriteWidgets .= $widget . “, “;
}
}
The script then repeats this process for the newsletter field:
if ( isset( $_POST[“newsletter”] ) ) {
foreach ( $_POST[“newsletter”] as $newsletter ) {
$newsletters .= $newsletter . “, “;
}
}
If any field values were sent for these fields, the resulting strings now have a stray comma and space on
the end, so the script uses a regular expression to remove these two characters, tidying up the strings:
$favoriteWidgets = preg_replace( “/, $/”, “”, $favoriteWidgets );
$newsletters = preg_replace( “/, $/”, “”, $newsletters );
You can find out more about regular expressions in Chapter 18.
Now it’s simply a case of outputting these two strings in the Web page, along with the other
single-value fields:
<dl>
<dt>First name</dt><dd><?php echo $_POST[“firstName”]?></dd>
<dt>Last name</dt><dd><?php echo $_POST[“lastName”]?></dd>
<dt>Password</dt><dd><?php echo $_POST[“password1”]?></dd>
241
9/21/09 7:23:40 PM
c09.indd 241
c09.indd 241 9/21/09 7:23:40 PM