|
Using an Array in a Form When you need to check, or validate, the fields submitted on a form, PHP is a great solution. When the form is self-submitted and checked for validation, you can collect the problems found, if any, and display them back to the user for correction. You can use an array to simply collect those 'errors'. The PHP code checking the form fields for validation would preceed the HTML and would need to be set up in a condition to execute on form submission only. (The following is used on my email forms.)
Starting with an empty array, such as $errorlist[], just assign it a string.
Your array is built with each additional string assignment.
If there are no errors found, I like to add the following to the errorlist (although not an error) to provide feedback to the user that the submission was successful. The user will see "Sending message..." until they're redirected to the confirmation page. To display the error array back to the user, the following code needs to exist within the body of the HTML. When the form first loads, errorlist is empty and the code doesn't execute.
<?php
if ($errorlist) {
echo "<center><div id=\"errorlist\"><p>";
foreach ($errorlist as $key => $value) {
echo "$value<br />\n";
}
echo "</p></div></center>";
}
?>
more coming soon |