-1

I do not succeed in sending the values of multiple checkboxes from a form with PHP mail.

This is piece of my form with the checkboxes:

<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">

In my php file i use this to settle the values form the multiple checkboxes:

$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] . " ");

    }

  }

In the body preparing for the email i use this:

  $body .= "Preferences: ";
  $body .= $preferences;
  $body .= "\n";

and to send the mail:

mail($to, $subject, $body, $headers)

The echoes are working fine: it echoes every selected value of the checkboxes But sending the email: it only sends the last checked checkbox value

What am I doing wrong?

Jack Maessen
  • 1,780
  • 4
  • 19
  • 51

2 Answers2

2

Why not use a foreach loop?

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;
  }
}

And the change to your code is to append the next line of text, you're currently overwriting it with $preferences = 'new value' each loop cycle.

The short hand is: $preferences .= 'new value', otherwise interpreted as $preferences = $preferences . 'new value';

Xorifelse
  • 7,878
  • 1
  • 27
  • 38
1

The problem is you just store on $preferences the last value, so you could useimplode on $selected_checkbox and get a list comma-separated so:

$body .= "Preferences: ";
$body .= implode(', ', $selected_checkbox);
$body .= "\n";
Averias
  • 931
  • 1
  • 11
  • 20