Gannicus
Gannicus

Reputation: 530

Creating a list of checkboxes with values from a php array as its label

I want to create a list of checkboxes with values from a php array as its label. I want it to look like

Here is the list of students whose schedules are saved:

[checkbox] Robb

[checkbox] Catelyn

[checkbox] Lady Stoneheart

but my code does not work.

Here's my code:

<?php

    $students = $_SESSION['students'];

    echo "Here is the list of students whose schedules are saved:<br/><br/>";

    echo "<form action='checkbox-form.php' method='post'>
    Load student?<br/>";

    foreach ($students as $stud) {

        echo "<br/><input type='checkbox' name=" . $stud . " value='load' />";
    }

    echo "<br/><br/><input type='submit' name='formSubmit' value='Submit' />
    </form>";

?>

The array is not the problem because it contains the proper values when I print it through foreach.

Upvotes: 0

Views: 14665

Answers (4)

twitch
twitch

Reputation: 225

foreach($students as $student){
echo "<br/><input type='checkbox' name=" . $student . " value=" . $student . " />";
echo "<label for name=" . $student . ">" . $student . "</label>";   
}   

Upvotes: 1

AbsoluteƵER&#216;
AbsoluteƵER&#216;

Reputation: 7880

It might be easier to do it this way:

On the form:

foreach ($students as $stud) {

    echo "<br/><input type='checkbox' name=\"students[]\" value='$stud' />$stud<br>";
}

On the handler to see what it's passing:

print_r($_POST);

Upvotes: 1

frankpinto
frankpinto

Reputation: 166

It looks like you've confused the "name" attribute for the label. A few notes:

  • "name" is used as the name of the parameter passed to the backend
  • "value" is the value that will be assigned to that parameter if the checkbox is checked

So the line in your foreach should look more like:

echo '<br /><input type="checkbox" name="students[]" value="'.$stud.'" />'.$stud;

If Robb and Catelyn are checked you will get the below in the $_POST['students'] variable server side:

Array
(
  [0] => Robb
  [1] => Catelyn
)

Upvotes: 1

dudewad
dudewad

Reputation: 13933

If all of the "value" fields are "load", which in this case they are, nothing can happen because your PHP won't see anything different value-wise. You should set the name value of all of these checkboxes to the same thing, and set the value to the student's name (though that's bad design- you should be setting the value to the numeric DB id that represents the student- what if you have students with the same name?)

So:

for($i = 0; i < count($students); $i++) {
    $s = $students[$i];
    echo "<br/><input type='checkbox' name="students[]" value='$s' />";
}

In this case name="students[]" is the students ARRAY which you can access via $_POST['students'] as an array.

Upvotes: 1

Related Questions