簡體   English   中英

如何通過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";
?>

為什么不遍歷數組以將所需的結果轉換為String?

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網站上的mail功能。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM