我在每个表格行中都有一个复选框,我想按下“保存”,这将循环遍历每个复选框: (如果选中)-> 输入该学生已参加的数据库 else ->输入该学生未参加的数据库。
我的 PHP 代码:
<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>
我在数据库中有一个“student_attendance”表,所以我想添加每个学生以及他/她的“已出席”复选框状态。干杯:D
最佳答案
// 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
}
}
此外,将复选框名称更改为 student['attendedCB']
,这应该可以工作。
关于php - 在 PHP 中循环复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44356249/