M.Ghali
M.Ghali

Reputation: 97

Loop over checkboxes in PHP

I have a checkbox in each table row, and I would like to press the "Save" which will loop over each checkbox: (if checked)-> enter to database that this student has attended else ->enter to database that this student has not attended.

enter image description here

My PHP code:

<table border="1" cellpadding="1" width="550px" style="text-align:center;">
    <th> Student ID </th>
    <th> First Name </th>
    <th> Last Name </th>
    <th> Class ID </th>
    <th> Attended </th>
<?php
    $classid = $_GET['classid'];

    $mysql_host='localhost';
    $mysql_user='root';
    $mysql_password='';
    $con = @mysqli_connect($mysql_host,$mysql_user,$mysql_password);

    if(!$con){
        die('Failed to connect to the database');//if not successful
    }else{
        //echo "Successfully connected to MySQL!";//if successful
        if(@mysqli_select_db($con, 'application_database')){//selecting the database
            //echo '<br>'."Connected to the specified database!";
        }else{
            die('<br>'."Could not connect to the specified database!");
        }
    }

    $sql="SELECT * FROM `student` WHERE class = '$classid'";
    $records=mysqli_query($con,$sql);

    while($student=mysqli_fetch_assoc($records)){

        echo "<tr>";
        echo "<td>".$student['id']."</td>";
        echo "<td>".$student['first_name']."</td>";
        echo "<td>".$student['last_name']."</td>";
        echo "<td>".$student['class']."</td>";
        echo "<td>".'<input type="checkbox" name="attendedCB">'."</td>";
    }

    echo '<form>';
    echo 'Teacher ID: <input type="number" name=teacher_id>';
    echo '<button name="save" type="submit">Save Attendance</button>';
    echo '</form>';


?>
</table>

I have a "student_attendance" table in the db, so I want to add each student along with his/her "attended" checkbox status. Cheers :D

Upvotes: 1

Views: 2756

Answers (2)

Luke Mlsna
Luke Mlsna

Reputation: 481

// loop per student
foreach ($_POST ['student'] as $student ) {
    extract($student) // extract array (lazy)
    // if they attended 
    if ( !empty ($attendedCB )) {
        // add them
        $query = "INSERT INTO your_table id,first,last,class,attendedCB VALUES($id, $first, $last, $attendedCB)";
        // then run that query or aggregate them all into one big one and run it
    }
}

Also, change the checkbox name to student['attendedCB'] and this should work.

Upvotes: 1

Kalaivani M
Kalaivani M

Reputation: 1290

Use id as value of check box by clicking that get the id value. Based on the id value you can do operations(update, delete, edit)

echo "<td><input type='checkbox' name='attendedCB' value ='.$student["id"].'></td>";

Upvotes: 0

Related Questions