0

I am trying to create a student attendance table that contains a checkbox for each students attendance, that is to be stored in a database.

This is my table that I have so far, that is executed from an ajax function call. Most of the data is from a database, that contains student names.

For the sake of this example $numStudent = 5;

echo '<form method="post" action="checkAttend.php"> 
    <table border="1">';
$count = 1;

while(($count < $numStudent) && ($students = mysqli_fetch_assoc($result))) {
    echo '<tr>
        <th>' . $count. '</th>
        <th>' . $students['student_name'] . '</th>
        <th> <input type="checkbox" name="students[]" /> </th>
    </tr>';
    $count++;
}

echo '<th colspan = "3">
    <input type="submit" name="button" id="button" value="Submit" /> </th>';
echo '</table>';
echo '</form>';

In checkAttend.php The form prints exactly the way I need it to, but when I try to print out the values in the checkbox array (to check what values are contained within before saving it to the database) each value in the array prints out :

$student_attend[0]       A
$student_attend[1]       r
$student_attend[2]       r
$student_attend[3]       a
$student_attend[4]       y

Typically I want to store some kind of value in the corresponding field in the database to indicate if the student is absent or not.

I cant tell if I am doing the checkbox loop correctly or not or if I need to add in more stuff.

2 Answers 2

1

You'll want to loop through the $student_attend array like the following:

foreach ($student_attend as $value) { 
  // do something with $value
}

More info on foreach here.

Sign up to request clarification or add additional context in comments.

Comments

0

If you want to add dynamic data with your checkboxes, then you can use it as follows: Inside the form tag you can use

    <form method="post" action="checkAttend.php"> 
    <table border="1">
    <?php
    $count=1;
    while($students = mysqli_fetch_assoc($result)) {
     ?>
     <tr>
      <th><?php echo $count;?></th>
      <th><?php echo $student['student_name']; ?></th>
      <th><input type="checkbox" name="students[]" value=<?php echo $student['student_id']; ?>/></th>
     </tr>
     <?php
    }
    ?>
</table>
</form>

and in checkAttend.php page write the following code:

if(isset($_POST['button'])){
  if(count($_POST['student_id'])>0){
   foreach($_POST['student_id'] as $student_id){
    mysql_query("update table_name set column_name = '1' where student_id = '".$student_id.'"); 
    // Just use the student id as checkbox value and update it as you just need the check or uncheck the checkbox.  
   }
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.