I'm working on a PHP project, where I have the following form to submit:
<h2>Create Subject</h2>
<form action="create_subject.php" method="post">
<p>Subject name:
<input type="text" name="menu_name" value="" />
</p>
<p>Position:
<select name="position">
<?php
$subject_set = find_all_subjects();
$subject_count = mysqli_num_rows($subject_set);
for ($count=1; $count <= ($subject_count + 1); $count++) {
echo "<option value=\"{$count}\">{$count}</option>";
}
?>
</select>
</p>
<p>Visible:
<input type="radio" name="visible" value="0" /> No
<input type="radio" name="visible" value="1" /> Yes
</p>
<input type="submit" name="submit" value="Create Subject" />
</form>`
In the create_subject.php (where the form action takes place), I have some validation, which looks like:
if(isset($_POST['submit'])) {
// Process the form
$menu_name = mysql_prep($_POST["menu_name"]);
$position = (int) $_POST["position"];
$visible = (int) $_POST["visible"];
//validations
$required_fields = array("menu_name", "position", "visible");
validate_presences($required_fields);
$fields_with_max_lengths = array("menu_name" => 30);
validate_max_lengths($fields_with_max_lengths);
if(!empty($errors)) {
$_SESSION["errors"] = $errors;
redirect_to("new_subject.php");
}
where the validate presence should function as check if the fields are empty and looks like:
function validate_presences($required_fields) {
global $errors;
foreach ($required_fields as $field) {
$value = trim($_POST[$field]);
if (!has_presence($value)) {
$errors[$field] = fieldname_as_text($field)." can't be blank";
}
}
}
But when I submit the form with missing data, instead of redirecting back to the previous page and listing all the errors stored in a session, I get the following error messages:
Notice: Undefined index: visible in /Users/eak/Sites/widget_corp/public/create_subject.php on line 10
Notice: Undefined index: visible in /Users/eak/Sites/widget_corp/includes/validation_functions.php on
line 22- Warning: Cannot modify header information - headers already sent by (output started at
/Users/eak/Sites/widget_corp/public/create_subject.php:10) in
/Users/eak/Sites/widget_corp/includes/functions.php on line 4
So the output started at where the $_POST["visible"] was detected as undefined. What can be the solution here?