tags:

views:

407

answers:

3

I have a column in my table titled 'authorised'. It's 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? I think MySQL might not have a true Boolean data type, as when I make it under phpMyAdmin it just becomes tinyint(1).

+5  A: 
UPDATE users SET `authorised` = IF (`authorised`, 0, 1)
nickf
This looks cleaner IMO. :)
alex
Just make sure you add your where clause, alex.
Peter Bailey
@Peter, thanks, and yes I did.
alex
+3  A: 

There are multiple ways to do this, here's a simple one:

UPDATE users SET authorised = ABS(authorised - 1) WHERE id = 2;
Chad Birch
Whoops, missed that. Thanks Chad.
alex
why not just "1 - authorised" ?
nickf
@nickf: I agree with you, the following should work: UPDATE users SET authorised = 1 - authorised WHERE id = 2;
dalle
Yep, that way will work just as well. There's no reason I went with the ABS() method, it's just the one that I thought of first. :b
Chad Birch
+8  A: 
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.

Alex Marshall
Ok, that didn't get posted properly, those slashes should be backticks, which are MySQLs default encapsulator.
Alex Marshall
That's a good one...! +1
alex