【问题标题】:how to send by mail values of multiple checkboxes with php [duplicate]如何使用php通过邮件发送多个复选框的值[重复]
【发布时间】:2018-08-17 05:04:45
【问题描述】:

我无法通过 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)

回显工作正常:它回显复选框的每个选定值 但是发送电子邮件:它只发送最后选中的复选框值

我做错了什么?

【问题讨论】:

  • 你每次都覆盖,试试:$preferences .= $selected_checkbox[$i];
  • 旁注:你不应该像那样连接$body;这很麻烦。
  • This Q&A 会帮助你。 foreach 最适合这个。它也可能是重复的。

标签: php forms


【解决方案1】:

问题是您只需将最后一个值存储在 $preferences 中,因此您可以在 $selected_checkbox 上使用implode 并获得一个以逗号分隔的列表:

$body .= "Preferences: ";
$body .= implode(', ', $selected_checkbox);
$body .= "\n";

【讨论】:

  • 现在完美运行!
【解决方案2】:

为什么不使用 foreach 循环?

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',否则解释为$preferences = $preferences . 'new value';

【讨论】:

    猜你喜欢
    • 2012-01-19
    • 2021-09-22
    • 1970-01-01
    • 1970-01-01
    • 2018-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多