<?php
if($_POST) {
//not empty
//atleast 6 characters long
$errors = array();
//start validation
if(empty($_POST['email'])) {
$errors['email1'] = "<p style='color:red;font-family: BCompset, Arial, Helvetica, sans-serif;font-size:30px;'>Please write down your email!</p>";
}
//check errors
if(count($errors) == 0) {
//redirect to success pages
header("Location: success.php");
exit();
}
}
?>
<form action="" method="POST" class="searchform" dir="ltr">
<input type="text" name="email" placeholder="Your email address"/>
<button name="submit" type="submit" class="btn btn-default"><i class="fa fa-arrow-circle-o-right"></i></button>
<p><?php if(isset($errors['email1'])) echo $errors['email1']; ?></p>
<?php if(count($errors) == 0){
echo "<p id='para' dir='rtl'>
You can add your email to get the latest updates.</p>";
} ?>
</form>
我希望在尚未提交表单时显示带有id ='para'(第31行)的段落,如果用户在未输入其电子邮件地址的情况下点击了提交按钮,则会弹出错误消息,该段落将不再显示..要做到这一点,我设置if(count($errors) == 0)
,但我在第31行得到未定义变量错误消息。也许是因为我不能从动作脚本中取一个变量,直到表单没有提交。请解决我的问题?
答案 0 :(得分:1)
试试这段代码: -
<?php
$errors = array();
if($_POST)
{
//not empty
//atleast 6 characters long
//start validation
if(empty($_POST['email']))
{
$errors['email1'] = "<p style='color:red;font-family: BCompset, Arial, Helvetica, sans-serif;font-size:30px;'>Please write down your email!</p>";
}
//check errors
if(count($errors) == 0)
{
//redirect to success pages
header("Location: success.php");
exit();
}
}
?>
<form action="" method="POST" class="searchform" dir="ltr">
<input type="text" name="email" placeholder="Your email address"/>
<button name="submit" type="submit" class="btn btn-default"><i class="fa fa-arrow-circle-o-right"></i></button>
<p><?php if(isset($errors['email1'])) echo $errors['email1']; ?></p>
<?php if(count($errors) == 0){echo "<p id='para' dir='rtl'>You can add your email to get the latest updates.</p>";}?>
</form>
答案 1 :(得分:1)
问题是您的<form>
超出了if($_POST)
,因此会显示是否设置了$_POST
。但$errors
仅在if
内设置。有两种简单的方法可以解决这个问题:
将$errors
的初始化移至if
之前。
使用if(empty($errors)
代替if(count($errors) == 0)
。如果变量未设置,empty()
不会抱怨。