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

(singke) #1
ptg16476052

Processing Forms 673

24


Then I wrote the PHP to validate my fields:


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


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


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


This function validates each of the fields on the form and then places all the errors in
separate error messages named $nameErr, $ageErr, and $toysErr, respectively. When an
error is detected, the error variable is updated with a string. Later on, I display the error
messages and use the field names to mark the fields that have errors.


On the first line, I check to see whether a form has been submitted via POST. Then I start
checking each field one at a time. PHP has a built-in function called empty() that checks
to see whether a variable is empty. In this case, I use it to check $_POST['name'], which
was set automatically when the form was submitted. If that variable is empty, meaning
that the user did not submit her name, I add an entry to $nameErr. If that value is not
empty, I assign the submitted information to the $name variable.


For the age field, I want to make sure that it is not empty and that it’s a number. The line
$agecheck = (isset($_POST['age'])? $_POST['age'] : null); assigns a variable
$agecheck to the submitted value if it is there and to null if it isn’t. This uses a short-
hand format for the if/then/else conditional statement. It is written in the following
format:


if? then : else ;


First the conditional statement, followed by a question mark, then the value if it’s true
followed by a colon, and finally the value if it’s false.



Free download pdf