PHP告诉我填写所有字段


PHP telling me to fill in all fields

好的,所以我有一个联系表格:

<?php
$body = "From: $name'n E-Mail: $email'n Message:'n $message";
if ($_POST['submit']) {
    if ($name != '' && $email != '') {
        if ($human == '4') {                 
            if (mail ($to, $subject, $body, $from)) { 
                echo '<p>Your message has been sent!</p>';
            } else { 
                echo '<p>Something went wrong, go back and try again!</p>'; 
            } 
       } else if ($_POST['submit'] && $human != '4') {
           echo '<p>You answered the anti-spam question incorrectly!</p>';
       }
   } else {
       echo '<p>You need to fill in all required fields!</p>';
   }
}

?>

以及与之配套的 HTML 代码:

<form action="" method="POST"> 
<!--PHP Code above goes here-->
<div>
<label>Name</label>
    <br>
    <input name="name" placeholder="Type Here">
</div>
<div>   
    <label>Email</label>
    <br>
    <input name="email" type="email" placeholder="Type Here">
</div>
<div>
    <label>Message</label>
    <br>
    <textarea name="message" placeholder="Type Here"></textarea>
</div>
<div> 
    <label>*What is 2+2? (Spam protection)</label>
    <br>
    <input name="human" placeholder="Type Here">
</div>
<input id="submit" name="submit" type="submit" value="Submit">
</form>

但即使填写了所有字段,它也会一直告诉我填写所有必填字段。提前谢谢。

您需要通过以下方式获取通过 POST 提交的所有变量的值: $email = _POST 美元["电子邮件"]

我已经检查并更正了您的代码。一切都很好,除了你必须声明 POST 变量:

<?php
  $body = "From: $name'n E-Mail: $email'n Message:'n $message";
  $name = $_POST['name'];
  $email = $_POST['email'];
  $human = $_POST['human'];
  $from = 'example@example.com';
  if ($_POST['submit']) {
    if ($name != '' && $email != '') {
      if ($human == 4) {                 
        if (mail ($email, $subject, $body, $from)) { 
            echo '<p>Your message has been sent!</p>';
        } else { 
            echo '<p>Something went wrong, go back and try again!</p>'; 
        } 
      } else if ($_POST['submit'] && $human != '4') {
       echo '<p>You answered the anti-spam question incorrectly!</p>';
     }
  } else {
   echo '<p>You need to fill in all required fields!</p>';
 }
}
?> 

您还应该使用 isset() 和 !empty() 函数检查表单字段是否已提交。

相关文章: