PHP SQL Update array

后端 未结 5 1562
南方客
南方客 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:13

    I would suggest you to use the following code:

    $theArray = array("1" => "1","2" => "2","3" => "3"); // The scheme is ID => Status
    
    $errorMsg = false; // Our default assumption is that no error occured
    
    foreach($theArray as $key => $value) {
        $sql = "UPDATE table SET status =".$value." WHERE id = ".$key;
    
        if(!db() -> query($sql)) { // Execute the query and check whether it failed
            $errorMsg = "Query for ID ".$key." failed.";
            break; // When the query failed we exit the loop and echo the error message
        }
    }
    
    if($errorMsg) { // If an error occured (errorMsg is no longer false) we echo it here
        echo $errorMsg;
    }
    

    Basically you do just create one array $theArray, which contains key => value pairs of the IDs and the statuses you want to give them. Afterwards, you loop through this array, execute the db() -> query() for each key => value pair and check whether it failed or not. If a query failed, you break the loop and output the error message.


    Advantages:

    • Instead of using two arrays ($array_id, $array_status) I do use only one associative array $theArray. The advantage here is that you only have one instead of two arrays and that you can extend the number of rows you'd like to change without changing your code. Just extend the array.
    • The array $theArray does not need to be in a chronological order and you can give each ID independently of the other IDs a status.
    • You are executing the db() -> query($sql) in your code two times. This is not very efficient and redundant. Instead you can execute the command only once and immediately check whether it failed or not based on its return value inside the if().
    • The errorMsg I am creating in the code let you know which query failed so it gives you a more detailed information for debugging.

提交回复
热议问题