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 =
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 ID
s and the status
es 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:
$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.$theArray
does not need to be in a chronological order and you can give each ID
independently of the other ID
s a status
.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()
.errorMsg
I am creating in the code let you know which query
failed so it gives you a more detailed information for debugging.