简体   繁体   English

在SQL和PHP中更新多行

[英]Updating multiple rows in sql and php

I have a table , that needs to update specific rows.The user ticks(using checkbox) which value to update and this is then sent as an array (the two values) This value(s) then needs to be changed in the database.The problem is it updates both values with the same. 我有一个需要更新特定行的表。用户勾选(使用复选框)要更新的值,然后将其作为数组发送(两个值),然后需要在数据库中更改此值。问题是它用相同的值更新两个值。 i need both values to be different based on whats coming in from the post array 我需要两个值都不同,这取决于帖子数组中的内容

I am not sure if i should use a join? 我不确定是否应该使用联接? or a for loop? 还是for循环?

How do you go about updating multiple values coming in from a checkbox array? 如何更新来自复选框数组的多个值? . All i want is for it to update both values based on the POST array values.The correct values are coming in from post array as i used var_dump 我想要的是基于POST数组值更新两个值。正确的值来自于我使用var_dump的post数组

foreach($_POST['course_id'] as $course_id) {

    $update_query = "UPDATE course_student SET course_id='$course_id' WHERE student_id='$student_id' ORDER BY course_id";
    $update_course_result = mysqli_query($connection,$update_query);

    if($update_course_result && mysqli_affected_rows($connection)>0) {
        echo "Success";
        // more code here
    }

}

The trick is to delete all the entries for the student first and re-insert the newly checked values afterwards: 诀窍是先删除该学生的所有条目,然后再重新插入新检查的值:

DELETE FROM course_student WHERE student_id='$student_id'

And then in your foreach-loop execute the following query: 然后在您的foreach循环中执行以下查询:

INSERT INTO course_student SET course_id='$course_id', student_id='$student_id'

This looks afterwards like an "update" because you removed everything (also the not checked ones). 此后看起来像“更新”,因为您删除了所有内容(还包括未选中的内容)。 And inserted all new checked entries. 并插入所有新的已检查条目。

And please take care of SQL-injections as mentioned in the comments above. 并且请注意上面注释中提到的SQL注入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM