form validation using arrays
Posted: Thu Dec 03, 2009 7:51 am
i need help with this form validation
if (isset($_POST['submit'])) {
$errors = array();
$required_fields = array('menu_name', 'position','visible');
foreach($required_fields as $fieldname) {
if (!isset($_POST[$fieldname]) || (empty($_POST[$fieldname]) && $_POST[$fieldname] != 0)) {
$errors[] = $fieldname;
}
}
$fields_with_lengths = array('menu_name' => 30);
foreach($fields_with_lengths as $fieldname => $maxlength ) {
if (strlen(trim(mysql_prep($_POST[$fieldname]))) > $maxlength) { $errors[] = $fieldname; }
}
if (empty($errors)) {
// Perform Update
$id = mysql_prep($_GET['subj']);
$menu_name = mysql_prep($_POST['menu_name']);
$position = mysql_prep($_POST['position']);
$visible = mysql_prep($_POST['visible']);
//update code
}
}
<form action="edit_subject.php?subj=<?php //myvalue passing here for the id you click on ?>" method="post">
<p>Subject name:
<input type="text" name="menu_name" value="<?php echo $sel_subject['menu_name']; ?>" id="menu_name" />
</p>
<input type="submit" name="submit" value="Edit Subject" />
</form>
the problem is that if don't enter something in the input type="text" the form still updates the subject to blank , now if i try submit again with a blank value the form doesn't go to update part which is what i want , but should not allow any blank values passing in the first place , so the array above is not empty, how can i achieve this using this arrays as above
any help greatly appreciated
if (isset($_POST['submit'])) {
$errors = array();
$required_fields = array('menu_name', 'position','visible');
foreach($required_fields as $fieldname) {
if (!isset($_POST[$fieldname]) || (empty($_POST[$fieldname]) && $_POST[$fieldname] != 0)) {
$errors[] = $fieldname;
}
}
$fields_with_lengths = array('menu_name' => 30);
foreach($fields_with_lengths as $fieldname => $maxlength ) {
if (strlen(trim(mysql_prep($_POST[$fieldname]))) > $maxlength) { $errors[] = $fieldname; }
}
if (empty($errors)) {
// Perform Update
$id = mysql_prep($_GET['subj']);
$menu_name = mysql_prep($_POST['menu_name']);
$position = mysql_prep($_POST['position']);
$visible = mysql_prep($_POST['visible']);
//update code
}
}
<form action="edit_subject.php?subj=<?php //myvalue passing here for the id you click on ?>" method="post">
<p>Subject name:
<input type="text" name="menu_name" value="<?php echo $sel_subject['menu_name']; ?>" id="menu_name" />
</p>
<input type="submit" name="submit" value="Edit Subject" />
</form>
the problem is that if don't enter something in the input type="text" the form still updates the subject to blank , now if i try submit again with a blank value the form doesn't go to update part which is what i want , but should not allow any blank values passing in the first place , so the array above is not empty, how can i achieve this using this arrays as above
any help greatly appreciated