如何将复选框值更新到数据库
$fmcourse = $_POST['fm_courses'];
foreach($fmcourse as $fmc) {
$studentid = mysqli_real_escape_string($con, $_POST["id"]);
$sql = "UPDATE enrollments SET course_fk='$fmc' WHERE student_fk = '$studentid'";
}
var_dump(fmc)
输出此
string(2) "18" string(2) "20" string(2) "22" string(2) "24" string(2) "26"
当我更新course_fk时,在所有行上重复相同的id
+-----+------------+-----------+
| eid | student_fk | course_fk |
+-----+------------+-----------+
| 1 | 1 | 17 |
| 2 | 1 | 17 |
| 3 | 1 | 17 |
+-----+------------+-----------+
我正在寻找这个
+-----+------------+-----------+
| eid | student_fk | course_fk |
+-----+------------+-----------+
| 1 | 1 | 17 |
| 2 | 1 | 20 |
| 3 | 1 | 22 |
+-----+------------+-----------+
答案 0 :(得分:1)
下面的代码使用函数 record_exists()检查,如果记录在enrollments表中有重复项,如果有,则代码只会相应地更新重复项。如果没有重复项,则会为学生创建新的注册记录。
更新了代码。
$fmcourse = $_POST['fm_courses'];
$student_id = $_POST["id"];
$batch_id = $_POST["name"];
delete_enrollments( $student_id, $batch_id );
foreach($fmcourse as $fmc) {
$course_id = $fmc;
if( record_exists( $student_id, $course_id, $batch_id ) == FALSE ) {
$stmt = mysqli_prepare($conn, "INSERT INTO enrollments (enrollment_id, student_id, course_id, batch_id, is_deleted, joining_date) VALUES( NULL, ?, ?, ?, 0, NOW() );");
$is_binded = mysqli_stmt_bind_param($stmt, "iii", $student_id, $course_id, $batch_id);
$is_exec = mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
}
else {
undelete_enrollment($student_id, $course_id, $batch_id);
}
}
function undelete_enrollment($student_id, $course_id, $batch_id) {
global $conn;
$stmt = mysqli_prepare($conn, "UPDATE enrollments SET is_deleted = 0, joining_date = NOW() WHERE student_id= ? AND course_id = ? AND batch_id = ?");
$is_binded = mysqli_stmt_bind_param($stmt, "iii", $student_id, $course_id,$batch_id);
$is_exec = mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
return $is_exec;
}
function record_exists( $student_id, $course_id, $batch_id ) {
global $conn;
$stmt = mysqli_prepare($conn, "SELECT COUNT(enrollment_id) as total FROM enrollments WHERE student_id= ? AND course_id = ? AND batch_id = ?");
$is_binded = mysqli_stmt_bind_param($stmt, "iii", $student_id, $course_id, $batch_id);
$is_exec = mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$record = mysqli_fetch_assoc($result);
mysqli_stmt_close($stmt);
return ( isset( $record['total'] ) AND $record['total'] > 0 );
}
function delete_enrollments( $student_id, $batch_id ) {
global $conn;
$stmt = mysqli_prepare($conn, "UPDATE enrollments SET is_deleted = 1 WHERE student_id = ? AND batch_id =?;");
$is_binded = mysqli_stmt_bind_param($stmt, "ii", $student_id, $batch_id);
$is_exec = mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
return $is_exec;
}
答案 1 :(得分:0)
您需要根据eid
而不是student_fk
您还需要eid
。随着您的student_fk
值重复出现。它总是更新最后一个值
因此您的where
条件存在问题。您需要添加eid
而不是student_fk
的条件。同时确保每行$eid
不同。
$sql = "UPDATE enrollments SET course_fk ='$fmc' WHERE eid = '$eid'";
此外,您的代码对SQL注入是开放的。为防止这种情况,请使用预备声明