Increment field of mysql database using codeigniter#39;s active record syntax(使用codeigniter的活动记录语法增加mysql数据库的字段)
问题描述
我有以下 php-codeigniter 脚本,它尝试使用活动记录语法增加记录的字段:
I have the following php-codeigniter script which attempts to increment a field of a record using active-record syntax:
$data = array('votes' => '(votes + 1)');
$this->db->where('id', $post['identifier']);
$this->db->update('users', $data);
这会产生以下 SQL:
This produces the following SQL:
"UPDATE
usersSET
votes='(votes + 1)' WHERE
id='44'
"
"UPDATE
usersSET
votes= '(votes + 1)' WHERE
id= '44'
"
它没有运行,但是这个 SQL 可以做我正在寻找的东西:"UPDATE
usersSET
votes= (votes + 1) WHERE
id='44'
"` <--注意周围缺少引号 (votes + 1)
Which doesn't run, but this SQL does do what I'm looking for:
"UPDATE
usersSET
votes= (votes + 1) WHERE
id= '44'
"` <--Note the lack of quotes around (votes + 1)
有谁知道如何使用 codeigniter 的活动记录语法来实现这种类型的查询?
Does anyone know how to implement this type of query with codeigniter's active record syntax?
推荐答案
您可以按照以下操作:
$this->db->where('id', $post['identifier']);
$this->db->set('votes', 'votes+1', FALSE);
$this->db->update('users');
之所以有效,是因为第三个(可选)FALSE 参数告诉 CodeIgniter 不要用反引号 ('
) 保护生成的查询.这意味着生成的 SQL 将是:UPDATE users SET votes= votes + 1 WHERE id='44'
如果您注意到,从 '(votes+1)'
中删除了反引号,这会产生将 votes 属性增加 1 的预期效果.
The reason this works is because the third (optional) FALSE parameter tells CodeIgniter not to protect the generated query with backticks ('
). This means that the generated SQL will be:
UPDATE users SET votes= votes + 1 WHERE id= '44'
If you notice, the backticks are removed from '(votes+1)'
, which produces the desired effect of incrementing the votes attribute by 1.
这篇关于使用codeigniter的活动记录语法增加mysql数据库的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用codeigniter的活动记录语法增加mysql数据库的字段


基础教程推荐
- while 在触发器内循环以遍历 sql 中表的所有列 2022-01-01
- MySQL根据从其他列分组的值,对两列之间的值进行求和 2022-01-01
- CHECKSUM 和 CHECKSUM_AGG:算法是什么? 2021-01-01
- ORA-01830:日期格式图片在转换整个输入字符串之前结束/选择日期查询的总和 2021-01-01
- 使用 VBS 和注册表来确定安装了哪个版本和 32 位 2021-01-01
- 如何在 CakePHP 3 中实现 INSERT ON DUPLICATE KEY UPDATE aka upsert? 2021-01-01
- 带更新的 sqlite CTE 2022-01-01
- MySQL 5.7参照时间戳生成日期列 2022-01-01
- 从字符串 TSQL 中获取数字 2021-01-01
- 带有WHERE子句的LAG()函数 2022-01-01