错误消息不以PHP形式显示

时间:2016-03-04 18:48:39

标签: php forms

如果用户留空,我的错误消息不会显示。它只需要我到我的操作页面,输入是空白的。为什么不显示我的错误?感谢。

<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;
}
?>

1 个答案:

答案 0 :(得分:3)

原因是,您的表单下面有PHP。将它放在HTML表单上方。

旁注:这回答了这个问题,并未涵盖您应该在初始页面加载时获得未定义的索引通知这一事实,具体取决于您的服务器的错误报告级别的设置方式。

<?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>
  • 因此,最好检查是否有任何设置/非空。

参考文献: