John Davidson

Switch status in Mysql table with PHP - the easiest way

0 comments
Message:


I have a Mysqli table called status with the columns ID, STATUS.


The STATUS can be 1 or 2 only.


I want to update the STATUS column the easiest way, so if the STATUS value is 1, update it to 2 and vice versa.


Normally I can do it like:


 $c=$mysqli->query('SELECT * FROM status WHERE id="1"' );
$kats=$c->fetch_assoc();
$status=$kats['status'];

if ($status == '1') {$newstatus = '2';} else {$newstatus = '1';}

$mysqli->query("UPDATE status SET status = '$newstatus' WHERE id=1" );

This will work, but is there an easier way, or maybe 1 row query for this? As the values are just changing from 1 to 2 or from 2 to 1 in one column.



My Answer:
>query("SELECT * FROM status");
while($row=$c->fetch_assoc()){
if($row['STATUS']==1){
$new_status = 2;
} else {
$new_status = 1;
}
$mysqli->query("UPDATE status SET STATUS=$new_status WHERE ID=".$row['ID']);
}

Rate this post

4 of 5 based on 1776 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us