php - 在 PHP 中循环复选框

标签 php mysql

我在每个表格行中都有一个复选框,我想按下“保存”,这将循环遍历每个复选框: (如果选中)-> 输入该学生已参加的数据库 else ->输入该学生未参加的数据库。

enter image description here

我的 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/

相关文章:

javascript - 如何从单选按钮中的数据库加载值?

php - 我想要选择具有相同值的记录,并且 joomla 的一个用户将其添加到数据库表中

php - 从远程服务器下载文件,下载完成后删除

php - 为动态搜索引擎php添加过滤器

php - 第 1 页之后分页不起作用?

php - 我正在执行查询,然后使用变量作为链接,但链接无法正常工作

php - 尝试远程连接到 mysql 时出现错误 2003 (HY000)

MySQL `SUM` 和 `GROUP BY` 结果中缺少数据

php - 如何在 Perl 中缓存和清除输出缓冲区?

php - Blueimp 仅选择特定行