Update query increment field plus 1 codeigniter

2019-01-25 22:50发布

I got a problem when trying to increment by 1 on given field in my db. I tried with and without active records.

My functions look like this (in my model)

function _set_reads($id){
$this->db->set('reads', 'reads+1', FALSE)
$this->db->where('id', $id);
$this->db->update('article');
}

and

function _set_reads($id){
$sql = 'update article set reads=reads+1 where id=?';
$this->db->query($sql, array($id));
}

I get the same error in both cases and it's the following error message:

Error Number: 1064

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'reads+1 WHERE `id` = '15'' at line 1

UPDATE `article` SET `reads` = reads+1 WHERE `id` = '15'

I am using the latest version of MAMP

4条回答
Viruses.
2楼-- · 2019-01-25 23:03

Solved it: I had to change

$this->db->set('reads', 'reads+1', FALSE)

to

$this->db->set('reads', '`reads+1`', FALSE)

Sorry for the post...

查看更多
ゆ 、 Hurt°
3楼-- · 2019-01-25 23:08

set() will also accept an optional third parameter ($escape), that will prevent data from being escaped if set to FALSE.

查看更多
看我几分像从前
4楼-- · 2019-01-25 23:13

-- Need small correction

$this->db->where('id', $id);
$this->db->set('set_row', '`set_row`+ 1', FALSE);

Thank You

查看更多
ら.Afraid
5楼-- · 2019-01-25 23:23

This was very helpful to @syyu

$this->db->where('id', $id);
$this->db->set('set_row', '`set_row`- 1', FALSE); // to decrement
查看更多
登录 后发表回答