Reputation: 7
If user leaves anything blank, my error messages do not display. It simply takes me to my action page where the input is blank. Why don't my errors display? Thanks.
<p><span class="error">* required field.</span></p>
<form name="form2" method="post" action="favorites.php">
Name: <input type="text" name="name" value="<?php echo $name;?>">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
Favorite Season:
<input type="radio" name="season" value="winter">Winter
<input type="radio" name="season" value="spring">Spring
<input type="radio" name="season" value="summer" checked>Summer
<input type="radio" name="season" value="fall">Fall
<span class="error">* <?php echo $seasonErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
Your name is: <?php echo $_POST["name"]; ?><br>
Your favorite season is: <?php echo $_POST["season"]; ?><br>
<?php
$nameErr = $seasonErr = "";
$name = $season = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
}
if (empty($_POST["season"])) {
$seasonErr = "Season is required";
} else {
$season = test_input($_POST["season"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
Upvotes: 0
Views: 70
Reputation: 74216
The reason being is, that you have your PHP below your form. Place it above your HTML form.
Sidenote: This answers the question and does not cover the fact that you should be getting undefined index notices on initial page load, depending on how your server's error reporting level is setup.
<?php
$nameErr = $seasonErr = "";
$name = $season = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
}
if (empty($_POST["season"])) {
$seasonErr = "Season is required";
} else {
$season = test_input($_POST["season"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<p><span class="error">* required field.</span></p>
<form name="form2" method="post" action="favorites.php">
Name: <input type="text" name="name" value="<?php echo $name;?>">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
Favorite Season:
<input type="radio" name="season" value="winter">Winter
<input type="radio" name="season" value="spring">Spring
<input type="radio" name="season" value="summer" checked>Summer
<input type="radio" name="season" value="fall">Fall
<span class="error">* <?php echo $seasonErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
Your name is: <?php echo $_POST["name"]; ?><br>
Your favorite season is: <?php echo $_POST["season"]; ?><br>
References:
Upvotes: 2