简体   繁体   中英

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?

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

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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