2012-08-16 73 views
0

我已經設置了聯繫表單,並將其設置爲通過電子郵件將回復發送給電子郵件帳戶。表單的一部分是一系列複選框,我需要將這些複選框顯示在電子郵件中作爲列表。這是我下面的代碼,它現在返回'Array'而不是複選框的值。有什麼建議麼?如何通過PHP從HTML表單發送多個複選框響應?

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 = "[email protected]"; 
$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."; 
?> 

感謝,

傑森

+1

你需要通過你的服務陣列使用foreach – 2012-08-16 14:44:16

回答

4

你應該加入(例如爆用 '')的數組元素到一個字符串。

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

感謝這工作完美! – jasonbradberry 2012-08-16 14:56:57

1

爲什麼不循環數組以獲得期望的結果到字符串?

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。

1

由於多個複選框存儲在$_POST['service']中,它本身就是一個數組,並且已經變成了二維。它的不同索引可以像這樣訪問:$_POST['service'][0]

要做點什麼$_POST['service'],您可以通過所有索引使用的foreach循環:

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

或者,使用implode()簡單地串聯所有索引。

0

您的輸入類型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網站上的郵件功能。

相關問題