I have a column in my table titled 'authorised'. Its default is 0. It needs to be changed to 1 when the user is authorised, but it must be able to be reset to 0. I know I could do this easily with 2 queries like so:
$authorised = Db::query('SELECT authorised FROM users WHERE id=2'); $newAuthValue = ($authorised['authorised']) ? 0 : 1; Db::query('UPDATE users SET authorised=' . $newAuthValue . ' WHERE id=2');
What I wanted to know, is there a way to do this with one query? To reverse a boolean value?
You can use Boolean Operator for this Here delete is your boolean field. This solution also works for none boolean fields such as int and tinyint where values are set to 0 or 1.
MySQL doesn't really have booleans. TRUE and FALSE are aliases to 1 and 0, and the BOOL column type is just an alias for TINYINT(1) . All expressions that appear to give boolean results actually return 0 or 1.
MySQL does not have a boolean (or bool) data type. Instead, it converts boolean values into integer data types (TINYINT). When you create a table with a boolean data type, MySQL outputs data as 0, if false, and 1, if true.
UPDATE users SET `authorised` = IF (`authorised`, 0, 1)
UPDATE `users` SET `authorised` = NOT `authorised` WHERE id = 2
This query will also work to negate the field, and is more inline with boolean syntax.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With