I am doing some basic validation on a form. I am generating an array ($errors[]), populating it with error messages, then echoing the errors out if there are any, or inserting the data into a database if there are no errors. The result of my code below is that only one of the statements below appears, regardless if I leave both empty. I am just counting the errors, then doing a for loop to increment the number, then reading the array. It appears that the array is not accumulating the error messages, because if I echo out $nerrors, regardless if both $lastname and $address are left empty, it shows = 1. What am I doing wrong? // Set array $errors = array(); if (empty ($lastname)) { $errors[] = "You didn't include a Last Name ."; } elseif (empty ($address)) { $errors[] = "You didn't include an Address ."; } // if there were errors, print out an error page and exit $nerrors = count ($errors); if ($nerrors > 0) { print ("<html><head><title>Error</title></head> <body><p>There were problems with your form. Please go back to the previous page and correct the following omissions:</p><ul>"); for ($i = 0; $i < $nerrors; $i++) { print ("<li>" . $errors[$i] . "</li>\n"); print ("</ul>\n</body>\n</html>"); } } else { $sql="INSERT INTO contacts (dateentered, category, type, date, firstname, lastname, organization, address, city, state, county, zip, phone, fax, email, notes) VALUES ('$dateentered', '$category', '$string', '$date', '$firstname', '$lastname', '$organization' , '$address', '$city', '$state', '$county', '$zip', '$phone', '$fax', '$email', '$notes')"; }
if (empty ($lastname)) { $errors[] = "You didn't include a Last Name ."; } if (empty ($address)) { $errors[] = "You didn't include an Address ."; } PHP: Should do it. Peace,
You should name your errors, just so it's easier to work with them // Set array $errors = array(); if (empty ($lastname)) { $errors['lastname'] = "<p>You didn't include a Last Name.</p>"; } // here if (empty ($address)) { $errors['address'] = "<p>You didn't include an Address.</p>"; } if(count($errors) > 0) { // return to form } else { // SQL! } PHP: Then you can just return to the form and just echo the specific error above its field.