mysql 根据选中的复选框数更新语句

mysql Update Statement depending on number of checkbox checked

问题陈述:

例如: 用户 1 selected 3 复选框并提交了表单,我们有大小为 3 的数组和 table 的更新 3 列。 用户 1 selected 6 复选框并提交了表单,我们有大小为 6 的数组和 table.

的更新 6 列

根据 OP 的评论,您可以使代码通用如下:

// Check if atleast one subject has been selected
$selectedSubjects = array_filter($subjectCheckList);

// If no subject selected
if (empty($selectedSubjects)) {
    $sql = "UPDATE subjectmaster 
            SET substatus = 0 
            WHERE rollno = '" . mysqli_real_escape_string($rollnumber) . "'";
} else {
    // Initialize the sql string
    $sql = "UPDATE subjectmaster 
            SET substatus = 1 ";

   $i = 1;
   foreach ($subjectCheckList as $subject) {
       $sql .= ", sub" . $i . " = '" . mysqli_real_escape_string($subject) . "' ";
   }

   $sql .= " WHERE rollno = '" . mysqli_real_escape_string($rollnumber) . "'";
}

另外,请注意 mysqli_real_escape_string 的用法。它有助于防止 SQL 注入。为了更好地防止 SQL 注入,您可以检查 How can I prevent SQL injection in PHP?

好吧,首先,不清楚每一列的默认值应该是多少。 由于您的 MySQL 列是由数字(sub1、sub2 等)设置的,因此您的表单应该以适当的值相应地表示它们。例如:

<input class="form-check-input" name="year-3-checkbox[]" type="checkbox" value="1">

这样,您可以轻松循环并更新 table(我假设子列是 TINYINT(1) DEFAULT NULL):

<?php
    if(isset($_POST['year-3-submit'])){
        if(!empty($_POST['year-3-checkbox'])){
            $subjectCheckList = array();
            $query = "UPDATE table SET ";
            foreach ($_POST['year-3-checkbox'] as $key => $value) {
              $query .= " sub" . $value . " = 1, " 
            }
            $query = substr($query, 0, -1);
        }
    }
?>

希望对您有所帮助 盖伊

您还可以使用 array_filter、array_combine 和 array_slice。

<?php

$subs = [':sub1',
         ':sub2',
         ':sub3',
         ':sub4',
         ':sub5',
         ':sub6',
         ':sub7',
         ':sub8',
         ':sub9'
];

// use $dataFromForm = array_filter($_POST['year-3-checkbox'])

$dataFromForm = ['11111',
                 '222222',
                 '3333333'];

$dbh = new PDO('mysql:host=localhost;dbname=test', 'root', '*******');


$sql = 'UPDATE test SET sub1 = :sub1, sub2 = :sub2, sub3 = :sub3, sub4 = :sub4, sub5 = :sub5, sub6 = :sub6, sub7 = :sub7, sub8 = :sub8, sub9 = :sub9';
$sth = $dbh->prepare($sql);
$sth->execute(array_combine(array_slice($subs, 0, count($dataFromForm), $dataFromForm)));