We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

How to swap 0 / 1 in database?

I have a database field which can be 0 or 1. I simply would like to swap it, I have the native SQL for it:

UPDATE dbo.Table1 SET col2 = col2 ^ 1;

and the Phalcon style:

$query = Phalcon\DI::getDefault()->get('db'); $query->update('Table', array('active'), array('active ^ 1'), array('conditions' => 'id = ?', 'bind' => $userId)))

well it turns 1 to 0 but never 0 to 1. So its a one way direction



85.5k
Accepted
answer
edited Oct '15

UPDATE Table SET active = IF(active=1, 0, 1);

here is the full code


$sth = \Phalcon\DI::getDefault()->get('db');->prepare("UPDATE 'Table' SET active = IF(active=1, 0, 1) WHERE `id` = :user_id");

        $sth->bindValue(':user_id', $user_id, \PDO::PARAM_INT);
        $sth->execute();
edited Oct '15

You original code is trying to update active ^ 1 as string, so SQL treats is as true.

Use code by @Izo , or try this: $query->update("Table", array("active"), array(new RawValue("active ^ 1")), ...



28.2k

yea, now I get it. But somehow the "array(new RawValue("active ^ 1"))" seems to work neither.