如何在提交表单并且出现错误后填充并显示$errors
变量?
<form method="post" action="<?php $_SERVER['PHP_SELF']; ?>">
<?php
if(!is_null($errors)) {
echo "<h3>$errors</h3>";
}
?>
<label for="Name">Name</label><em>(Required)</em>
<input type="text" name="Name"/>
<label for="Email">Email</label><em>(Required)</em>
<input type="text" name="Email"/>
<label for="Website">Website</label>
<input type="text" name="Website"/>
<label for="Message">Message</label><em>(Required)</em>
<textarea name="Message"></textarea>
<button id="submit" type="submit" value="submit"name="submit">Submit</button>
<input type="hidden" name="Submit" />
</form>
和我的脚本来处理表单
$errors = null;
if(isset($_POST['submit'])) {
if(!empty($_POST['Name']) && !empty($_POST['Email']) && !empty($_POST['Message'])) {
$name = $_POST['Name'];
$email = $_POST['Email'];
$website = $_POST['Website'];
$message = $_POST['Message'];
//strip any html tags and slashes off of the fields
$nameClean = strip_tags($name);
$emailClean = strip_tags($email);
$websiteClean = strip_tags($website);
$messageClean = strip_tags($message);
$messageCleanAndStripped = stripslashes($messageClean);
}
} else {
$errors = "Please fill in the required fields";
}
答案 0 :(得分:4)
$ errors,因为这就是您的代码所做的事情:
if(isset($_POST['submit']))
{
....
}
else
{
$errors = "Please fill in the required fields";
}
这意味着如果用户第一次加载页面,他没有发布任何内容,因此isset($ _ POST ['submit'])为false,然后您将错误消息分配给$ errors变量。您应该将代码更改为:
if(isset($_POST['submit'])) {
if(!empty($_POST['Name']) && !empty($_POST['Email']) && !empty($_POST['Message'])) {
$name = $_POST['Name'];
$email = $_POST['Email'];
$website = $_POST['Website'];
$message = $_POST['Message'];
//strip any html tags and slashes off of the fields
$nameClean = strip_tags($name);
$emailClean = strip_tags($email);
$websiteClean = strip_tags($website);
$messageClean = strip_tags($message);
$messageCleanAndStripped = stripslashes($messageClean);
}
else
{
$errors = "Please fill in the required fields";
}
}
只需在条件中插入else语句,这样只有在用户实际提交内容时才会检查错误。
希望它有所帮助。
答案 1 :(得分:2)
你有if-else错误匹配。这样做:
if(isset($_POST['submit']))
{
if(!empty($_POST['Name']) && !empty($_POST['Email']) && !empty($_POST['Message']))
{
$name = $_POST['Name'];
$email = $_POST['Email'];
$website = $_POST['Website'];
$message = $_POST['Message'];
//strip any html tags and slashes off of the fields
$nameClean = strip_tags($name);
$emailClean = strip_tags($email);
$websiteClean = strip_tags($website);
$messageClean = strip_tags($message);
$messageCleanAndStripped = stripslashes($messageClean);
}
else
{
$errors = "Please fill in the required fields";
}
}