如何通过 php 从 HTML 表单发送多个复选框响应


How to send multiple checkbox responses from HTML form via php?

我已经设置了一个联系表单,并将其设置为通过电子邮件将回复发送到电子邮件帐户。表单的一部分是一系列复选框,我需要让这些复选框以列表的形式显示在电子邮件中。这是我在下面拥有的代码,目前返回"Array"而不是复选框的值。有什么建议吗?

.HTML:

<h3>Service required:</h3>
<input type="text" id="name" name="name" placeholder="Name" required />
<input type="email" id="email" name="email" placeholder="Email" required />
<input class="check-box styled" type="checkbox" name="service[]" value="Service / repairs" /><label> Service / repairs</label>
<input class="check-box styled" type="checkbox" name="service[]" value="MOT" /><label> MOT</label>
<input class="check-box styled" type="checkbox" name="service[]" value="Cars for sale" /><label> Cars for sale</label>

这是 php:

<?php
    if (isset($_POST['service'])) {
    $service = $_POST['service'];
    // $service is an array of selected values
}
$formcontent= "From: $name 'n Service(s) required: $service 'n";
$recipient = "name@email.com";
$subject = "You have a new message from $name";
$mailheader = "From: $email 'r'n";
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
echo "Thank You! We will get back to you as soon as we can.";
?>

谢谢

杰森

你应该将数组元素连接(例如,用', '内爆)到一个字符串中。

<?php
$formcontent= "From: $name 'n Service(s) required: ".implode(", " ,$service)." 'n";
?>

为什么不遍历数组以获得所需的结果到字符串中?

if (isset($_POST['service'])) {
    $service = $_POST['service'];
    // $service is an array of selected values
    $service_string = "";
    for($i=0;$i<count($service);$i++)
    {
        if($i!=0)
        {
            $service_string = $service_string . ", ";
        }
        $service_string = $service_string . $service[$i];
    }
}

然后,您将获得每个勾选项目的逗号分隔列表的输出,作为 $service_string。

由于$_POST['service']中存储了几个复选框,它本身就是一个数组,并且已经变成了二维的。它的不同索引可以像这样访问:$_POST['service'][0] .

要对 $_POST['service'] 执行某些操作,您可以使用 foreach 遍历所有索引:

foreach($_POST['service'] as $post){
    //Do stuff here
}

或者,使用 implode() 简单地连接所有索引。

您的输入类型 checkbix 必须具有唯一的名称。否则,最后一个复选框将在 $_POST 中找到。或者您可以如上所述进行循环访问。使您的电子邮件 html 格式并编写一串 html 以$formcontent。例如

$formcontent = "<html><head></head><body>";
$formcontent .= "<ul><li>".$_POST["checkbox1"]."</li>";
$formcontent .= "<li>".$_POST["checkbox2"]."</li>";
$formcontent .= "</ul></body></html>";

要以html格式编写电子邮件,请参阅php网站上的邮件功能。