我一直在颠倒浏览该php表单,但是我没有找到为什么不显示错误消息,并且即使所有字段为空,该表单也会始终发送电子邮件。有我的代码:
<form name="contactform" method="post" action="">
<input type="text" data-placeholder="<?php echo $name; ?>"name="name">
<input type="text" data-placeholder="<?php echo $email; ?>"name="email">
<textarea data-placeholder="<?php echo $message; ?>" name="message" rows="10"></textarea>
<input type="submit" name="submit" class="btn btn-footer" value="ENVOYER" id="btnContact">
<p class="text desktop"><?php echo $emailErr; ?></p>
</form>
<?php
if(isset($_POST['submit'])) {
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$emailErr = "";
if (!isset($name) || $email=="" || $message=="" ) {
$emailErr = "All fields are mendatory";
} else {
$mailTo = "test@gmail.com";
mail($mailTo);
$emailErr = "Email Send";
}
}
?>
答案 0 :(得分:1)
if (empty($name) || empty($email) || empty($message))
{
$emailErr = "All fields are mendatory";
}
您可以使用php函数为空或is_null
答案 1 :(得分:0)
isset()
将始终返回true,因为已设置了变量(为空字符串)。要检查变量是否为空,应使用对$email
和$message
所做的操作:
if ( $name == "" || $email == "" || $message == "" ) {
为演示,您只需运行以下命令即可:
$a = ""
var_dump(!isset($a)); // false
var_dump($a == ""); // true
答案 2 :(得分:0)
提交表单后,如果存在字段名称,则isset()
将返回true。但是,如果您检查任何字段的空值,则可以使用empty($fieldname)
或$fieldname == ""
或$fieldname == NULL
。
尝试一下:
if(isset($_POST['submit'])) {
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$emailErr = "";
if (empty($name) || empty($email) || empty($message) ) {
$emailErr = "All fields are mendatory";
} else {
$mailTo = "test@gmail.com";
mail($mailTo);
$emailErr = "Email Send";
}
}
答案 3 :(得分:0)
请尝试这个,
我在本地系统中检查了它的工作正常,错误和成功消息,这是根据您的要求
<?php
if(isset($_POST['submit'])) {
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$emailErr = "";
if (!isset($name) || $email=="" || $message=="" ) {
$emailErr = "All fields are mendatory";
} else {
$mailTo = "test@gmail.com";
mail($mailTo);
$emailErr = "Email Send";
}
}
?>
<form name="contactform" method="post" action="">
<input type="text" data-placeholder="<?php echo $name; ?>"name="name">
<input type="text" data-placeholder="<?php echo $email; ?>"name="email">
<textarea data-placeholder="<?php echo $message; ?>" name="message" rows="10"></textarea>
<input type="submit" name="submit" class="btn btn-footer" value="ENVOYER" id="btnContact">
<p class="text desktop"><?php echo $emailErr; ?></p>
</form>