I'm learning by way of tutorials, and the instructor used a validation routine that I'm confused about.
On the form page, he has input fields with the following names:
- menu_name
- position
- visible
On the form processing page, he has the following block of php (let's call it block A):
$menu_name = mysql_prep($_POST['menu_name']);
$position = mysql_prep($_POST['position']);
$visible = mysql_prep($_POST['visible']);
Below this block is another php block that inserts the data into MySQL -- this all works fine.
He then added the following php block above block A (let's call it block B):
$errors = array();
$required_fields = array('menu_name', 'position', 'visible');
foreach ($required_fields as $fieldname) {
if (!isset($_POST[$fieldname]) || empty($_POST[$fieldname])) {
$errors[] = $fieldname;
}
}
if (!empty($errors)) {
redirect_to("new_subject.php");
exit;
}
Question 1
I'm confused why in his $required_fields array, he is referencing the field names directly. Why not move block A above block B and then just reference the variables that were assigned from the $_POST?
Then just use those variables in the if statement within the foreach loop.
I guess I'm asking if my alternative approach is valid? Is there an apparent reason for why he took his approach?
(FYI the mysql_prep is a custom function he built to remove slashes and such.)
Question 2
If I'm understanding his code correctly, his first if statement is testing if the $fieldname is !isset (i.e. not set) or empty.
What's the difference? Since I don't know the difference, I'm also not clear on why he used the || operator. Can you please explain?
Question 3
And finally, it seems his first if statement is capturing any errors and putting them into the $errors array at the top of block B.
He then uses a second if statement to check if that $errors array has anything in it, and re-directs + exits if it does.
Is there a discernible reason for this approach? In my mind, it seems the first if statement could redirect + exit if any errors were found. Why capture them in that $errors array?