PHP SQL Update array

后端 未结 5 1559
南方客
南方客 2021-01-28 02:49

I originally was satisfied with the following in order to update row 1 and row 2 to the same value (status=1)

if ($_POST){
    $sql =\"UPDATE table SET  status =         


        
5条回答
  •  青春惊慌失措
    2021-01-28 03:19

    You can loop through the arrays using a for loop and exec a query for each one (Radu Vlad answer), or you can build a long query and execute it once, something like this:

    if ($_POST){
        $sql = ""; // Blank string
        $len = count($array_id); // Number of iterations
        for ($i = 0; $i < $l; $i++) { // Enter the loop
            $sql .= "UPDATE 
                      table
                    SET
                      status = {$array_status[$i]}
                    WHERE id = {$array_id[$i]};"; // Append the query
        }
        db()->query($sql);
    
        if(db()->query($sql)){
            echo "Update Successful";
        } 
        else{
            echo "Update Unsuccessful";
        }
    }
    

    When the val of $i is 0, then $array_id[$i] will print the first element, when $i is 1, $array_id[$i] will print the second element, and so on.

    Using .= you append text to a string. By the end of the loop, $sql will be a string with 3 queries ('UPDATE ... SET ...; UPDATE ... SET ...; UPDATE ... SET ...;').

    Not sure if it's the best way, though. But you get the idea.

提交回复
热议问题