I am doing a tutorial on PHP. I am in the update section of the CRUD lesson and am working on a validation script. I have followed the code exactly... I think but still not working correctly. Here is the problem: When I click submit to try to test the validation with the menu name field empty it goes through without an error... and updates the nav with an empty list item? I have looked over the code and all seems to be correct but I am very new to this so problems are easily overlooked.
Here is the code:
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;
}
}
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']);
$query = "UPDATE subjects SET
menu_name = '{$menu_name}',
position = {$position},
visible = {$visible} WHERE id = {$id}";
$result = mysql_query($query, $connection);
if(mysql_affected_rows() == 1){
// success
$message = "Subject was sucessfully updated";
}else{
$message = "The subject update failed.";
$message .= "<br />" . mysql_error();
}
}else{
//error occured
$message = "There were " . count($errors) . " errors in the form.";
}
} // end if(isset($_POST['submit']) )
?>
And the code from the body:
<h2>Edit Subject: <?php echo $sel_subject['menu_name']; ?></h2>
<?php
if(!empty($message)){
echo "<p class=\"message\">" . $message . "</p>";
}
?>
<?php
if(!empty($errors)){
echo "<p class=\"errors\">";
echo "Please review the folowing fields: <br />";
foreach($errors as $error){
echo "-" . $error . "</p>";
}
}
?>
Now when I change (empty($_POST[$fieldname]) to (empty($_POST['menu_name']) it spits out errors but they are for the position and visible fields which happen to be correct...? Is there a character left out that I just cannot see. I have done mostly copy and paste to prevent those stupid kind of mistakes.. Note: that the validation for position and visible do work... I think... since you cannot leave those fields blank anyway how would I know...
Any help is greatly appreciated.