以联系方式处理checbox

时间:2017-04-15 17:26:52

标签: php

我正在创建一个php表单,我按照正常方式处理复选框 但是在这段代码中,它始终打印不,问题是什么?

<form method="post" action="php/form.php">
  <div class="form-check pull-left">
  <label class="form-check-label">
    <input class="form-check-input" type="checkbox" value="yes" name="check1">
    Option one is this and that&mdash;be sure to include why it's great
  </label>
</div>
</form>

if (isset($_POST['check1'])) {
  $check1 = "yes";
} else {
  $check1 = "no";
}
$body="check1: $check1";
mail('email@mail.com', $subject, $body)

我总是收到没有

的电子邮件

2 个答案:

答案 0 :(得分:0)

如果您没有提交输入,这是正常的。 并且包装你的邮件功能,检查$ _POST是否为空。

试试这个:

<form method="post">
  <div class="form-check pull-left">
  <label class="form-check-label">
    <input class="form-check-input" type="checkbox" value="yes" name="check1" checked>
    Option one is this and that&mdash;be sure to include why it's great
  </label>
</div>
<input type="submit" value="ok">
</form>
<?php

if (isset ($_POST) && !empty ($_POST))
{
   if (isset($_POST['check1'])) {
     $check1 = "yes";
   } else {
     $check1 = "no";
   }
   $body="check1: $check1";
   mail('email@mail.com', $subject, $body)
}

答案 1 :(得分:0)

首次加载页面时,未发布任何内容,因此$_POST为空且$_POST['check1'] == NULL

根据您的逻辑,在这种情况下,您将check1设置为no并发送电子邮件(即使没有发布任何内容)。

您应该确保发布了一些内容,这可以通过在表单中​​添加submit按钮来完成

<button type="submit" name="submit">Submit POST</button>

并检查是否存在$_POST['submit']

if (isset($_POST['submit'])) 

所有在一起:

<form method="post">
    <div class="form-check pull-left">
        <label class="form-check-label">
            <input class="form-check-input" type="checkbox" value="yes" name="check1">
            Option one is this and that&mdash;be sure to include why it's great
        </label>
        <button type="submit" name="submit">Submit POST</button>
    </div>
</form>

<?php

if (isset($_POST['submit'])) {
    if (isset($_POST['check1'])) {
        $check1 = "yes";
    } else {
        $check1 = "no";
    }
    $body = "check1: $check1";
    mail('email@mail.com', $subject, $body)
}

这样,只有当用户实际提交表单时才会发送电子邮件,而不是每次加载页面时都会发送。