I have a form, it's to display all students in my school. Each student is displayed from a database and is shown as a checkbox - the name of the checkbox is the student ID.

On the submitted page I loop through the students table again and do this

while($row2 = $result2->fetch_assoc()){
	$StudentID = $row2['StudentID ']; 

if ($_POST["$StudentID "] == 1){
....

To see if they are checked or not but i get this error

Notice: Undefined offset: 460 in C:\wamp64[url]www..[/url]...

What is the best way of doing this?

    Checkbox elements only get submitted if they're checked, so I'm guessing that's your issue. There might be a more efficient way to approach this, but this simple fix might be:

    if(isset($_POST[$StudentID]) and $_POST[$StudentID] == 1) {
    

    PS: I just noticed you were added a spaces at the end of the array keys by putting them in quotes with a space at the end, is that on purpose, and if so, why?

      That does fix it, thanks!

      So what is the best way to do this. I know this works but have always wondered if this approach is the best way.

        I might use array notation for the checkbox names, and make their values the name you want to track, e.g. if you're populating the checkboxes in a loop...

        <input type="checkbox" name="students[]" value="<?php echo $studentID; ?>" /> <?php echo $studentName; ?>
        

        ...then you could loop through the ones that were checked in the form handler...

        if(!empty($_POST['students'])) {
            foreach($_POST['students'] as $studentID) {
                // do something with $studentID
            }
        }
        

          I might suggest defining an array of the checkboxes you want to check in a separate var:

          $checkboxes_to_check = array("StudentID", "checkbox1", "checkbox2", "checkbox3");
          foreach ($checkboxes_to_check as $cb) {
            // check $_POST[$cb] somehow?
          }
          
            Write a Reply...