Sams Teach Yourself HTML, CSS & JavaScript Web Publishing in One Hour a Day

(singke) #1
ptg16476052

676 LESSON 24: Taking Advantage of the Server


As you can see, the code for marking the label for the field as an error is the same for this
field as it was for name. The more interesting section of the code here is the loop that cre-
ates the check boxes.
The values and labels in the <input> tags are in an array I called $options. I then walked
through that array with the foreach function, calling each entry $option. Inside the loop,
I print out the <input> tags, using toys[] as the parameter name to let PHP know that
this field can have multiple values and should be treated as an array. I include the value
of the tag as $option, and I use it again to print out the label for the check box after the
tag. The last bit here is the if statement found within the <input> tag. Remember that if
you want a check box to be prechecked when a form is presented, you have to include the
checked attribute. I use the in_array() function to check whether the option currently
being processed is in $toys. If it is, I then print out the checked attribute using echo().
This ensures that all the items the user checked before submitting the form are still
checked if validation fails.
A browser displaying a form that contains some errors appears in Figure 24.2. Here’s the
full source listing for the page:

Input ▼
<?php
// define variables
$nameErr = $ageErr = $toysErr = "";
$name = $age = "";
$toys = array();

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if ( empty( $_POST['name'] ) ) {
$nameErr = 'You must enter your name.';
} else {
$name = $_POST['name'];
}

$agecheck = (isset($_POST['age'])? $_POST['age'] : null);
if ( !is_numeric( $agecheck ) ) {
$ageErr = "You must enter a valid age.";
} else {
$age = $_POST['age'];
}

if ( empty( $_POST['toys'] ) ) {
$toysErr = 'You must choose at least one toy.';
} else {
$toys = $_POST['toys'];
}
}


Free download pdf