1

I am trying to update records using mysql IF condition, is this supported as records are not updating

$this->db->update(
    'elections',
        array(
            'status'=>'IF(status=="Active","Inactive","Active")'
        ),
        array(
            'election_id'=>$election_id
        )
    );

I am getting following query on print:

UPDATE `elections` SET `status` = 'IF(status==\"Active\",\"Inactive\",\"Active\")' WHERE `election_id` = '8'

2 Answers 2

2

It seems CodeIgniter escapes your IF statement, but you can use it as string:

$this->db->query('UPDATE `elections` SET `status`= IF(`position`=?,?,?) WHERE `election_id` = ?', array('Active','Inactive','Inactive', $election_id));

Or
You can disable the auto escaping function (with set to false the third parameter of the set method):

$this->db->set('status', "IF(status='Active','Inactive','Active')", false)
->where(array('id' => $election_id))
->update('elections');

(Please keep in mind: in this case if your parameters can contain untrusted values you should escape them. e.g.: $this->db->escape)

Sign up to request clarification or add additional context in comments.

1 Comment

My question is about db->update method, is there any way to perform same query using update method ?? writing queries is messy code
0

Use a single equal (=) sign after status:

$this->db->update(
    'elections',
        array(
            "status"=>"IF(status='Active','Inactive','Active')"
        ),
        array(
            'election_id'=>$election_id
        )
    );

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.