Forum Moderators: coopster

Message Too Old, No Replies

to put checkbox for the data from the database

         

harish2011

7:01 pm on Sep 17, 2011 (gmt 0)

10+ Year Member



Hi, Iam new to php. I need an idea on how to put a checkboxes to the data that i have in my table of mysql db. For example there are 100 students record in the data base, i want to check how many students have been present for the exams on a particular day for a particular subject. the data should appear on the html page which has a checkbox next to the rollno of the students and by default they should have been checked, if we uncheck the checkbox it should be stored in the database and give a report for absentee students. please help me in getting the soulution if possible with code.

rocknbil

4:39 pm on Sep 19, 2011 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



There are about a thousand ways to do this . . . I would use a boolean or tinyint(1) in the database that defaults to 0 (zero.) If the box is checked, update the record to 1, if it's not, do nothing - the 0 will fill in by default.

The exception might be if there is a user error (it's set to 1 in error) and the student was absent, you'd then want to always update the field is there's no value:

$is_present = (isset($_POST['student_field_name']))?1:0;

$query = "update table set is_present=$is_present where record_id=$your_record";

An interesting thing about checkboxes - if a checkbox is not checked, it won't be present in $_POST, $_GET, or $_REQUEST. This might shed a little light on the above ternary.

The way you handle it in forms is really a matter of preference. I like to use actual named form field names/variables so I can look for solid values:

$counter=0;
foreach ($students as $student=>$is_present) {
// $is_present will be 1 or 0
$counter++;
$field_name = 'present_'.$counter; // (present_1, present_2, etc.)
echo "<input type=\"checkbox\" name=\"$field_name\" id=\"$field_name\" value=\"$is_present\">";
}

Then when submitted, I look for the marker

foreach ($_POST as $key => $value) {
if (preg_match('/present\_\d+/',$key)) {
// do the update
}
}

Of course, as mentioned, if it's not checked and I always want to update, I'd do something else . . .

Most PHP coders like to use arrays:

foreach ($students as $student=>$is_present) {
echo "<input type=\"checkbox\" name=\"is_present[ ]\" value=\"$is_present\">";
}

Matter of preference.