我没有成功使用PHP邮件从表单中发送多个复选框的值。
这是我的表单中的复选框:
<input type="checkbox" name="registercheckbox[]" value="saturday-16:00">
<input type="checkbox" name="registercheckbox[]" value="saturday-17:00">
<input type="checkbox" name="registercheckbox[]" value="saturday-18:00">
在我的php文件中,我用它来解决多个复选框的值:
$selected_checkbox = $_POST['registercheckbox'];
if(empty($selected_checkbox)) {
echo("you have to chose at least 1 checkbox!");
}
else {
$N = count($selected_checkbox);
echo('Your preferences are: ');
for($i=0; $i < $N; $i++) {
$preferences = $selected_checkbox[$i];
echo($selected_checkbox[$i] . " ");
}
}
在准备发送电子邮件的正文中,我使用了这个:
$body .= "Preferences: ";
$body .= $preferences;
$body .= "\n";
并发送邮件:
mail($to, $subject, $body, $headers)
回声正常工作:它回显了复选框的每个选定值 但是发送电子邮件:它只发送最后检查的复选框值
我做错了什么?
答案 0 :(得分:1)
为什么不使用foreach循环?
numpy
对代码的更改是附加下一行文本,您当前正在使用if(empty($selected_checkbox)) {
echo("you have to chose at least 1 checkbox!");
} else {
$preferences = ''; // avoid php info messages.
foreach($selected_checkbox as $value){
$preferences .= $value . PHP_EOL;
}
}
每个循环周期覆盖它。
简写为$preferences = 'new value'
,否则解释为$preferences .= 'new value'
答案 1 :(得分:1)
问题是你只是在$ preference上存储最后一个值,所以你可以在implode
上使用$selected_checkbox
并以逗号分隔这样的列表:
$body .= "Preferences: ";
$body .= implode(', ', $selected_checkbox);
$body .= "\n";