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数据库的字段


- SQL 临时表问题 2022-01-01
- 更改自动增量起始编号? 2021-01-01
- 远程 mySQL 连接抛出“无法使用旧的不安全身份验证连接到 MySQL 4.1+"来自 XAMPP 的错误 2022-01-01
- 以一个值为轴心,但将一行上的数据按另一行分组? 2022-01-01
- 如何将 Byte[] 插入 SQL Server VARBINARY 列 2021-01-01
- 如何将 SonarQube 6.7 从 MySQL 迁移到 postgresql 2022-01-01
- 在SQL中,如何为每个组选择前2行 2021-01-01
- 使用 Oracle PL/SQL developer 生成测试数据 2021-01-01
- 如何使用 pip 安装 Python MySQLdb 模块? 2021-01-01
- 导入具有可变标题的 Excel 文件 2021-01-01