如何使用类似if条件的mysql语法来使用codeigniter表更新?

时间:2022-10-06 12:32:57

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

我正在尝试使用mysql IF条件更新记录,这是否支持记录不更新

$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 个解决方案

#1


2  

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

似乎CodeIgniter转义了IF语句,但您可以将其用作字符串:

$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):

或者可以禁用自动转义函数(设置为false,设置方法的第三个参数):

$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)

(请记住:在这种情况下,如果您的参数可以包含不可信的值,那么应该转义它们。例如:$ this - > db - >逃跑)

#2


0  

Use a single equal (=) sign after status:

使用一个等号(=)后的状态:

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

#1


2  

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

似乎CodeIgniter转义了IF语句,但您可以将其用作字符串:

$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):

或者可以禁用自动转义函数(设置为false,设置方法的第三个参数):

$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)

(请记住:在这种情况下,如果您的参数可以包含不可信的值,那么应该转义它们。例如:$ this - > db - >逃跑)

#2


0  

Use a single equal (=) sign after status:

使用一个等号(=)后的状态:

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