MySQL 使用codeigniter的活动记录语法增加mysql数据库的字段
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6373564/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Increment field of mysql database using codeigniter's active record syntax
提问by Casey Flynn
I have the following php-codeigniter script which attempts to increment a field of a record using active-record syntax:
我有以下 php-codeigniter 脚本,它尝试使用 active-record 语法增加记录的字段:
$data = array('votes' => '(votes + 1)');
$this->db->where('id', $post['identifier']);
$this->db->update('users', $data);
This produces the following SQL:
这将产生以下 SQL:
"UPDATE
usersSET
votes= '(votes + 1)' WHERE
id= '44'
"
"UPDATE
用户SET
投票= '(votes + 1)' WHERE
编号= '44'
“
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)
哪个没有运行,但是这个 SQL 确实做了我正在寻找的:
"UPDATE
用户SET
投票= (votes + 1) WHERE
id = '44'
"` <--注意周围缺少引号 (votes + 1)
Does anyone know how to implement this type of query with codeigniter's active record syntax?
有谁知道如何使用 codeigniter 的活动记录语法来实现这种类型的查询?
回答by Boban
You can do as given below:
您可以按照以下说明进行操作:
$this->db->where('id', $post['identifier']);
$this->db->set('votes', 'votes+1', FALSE);
$this->db->update('users');
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.
这样做的原因是因为第三个(可选)FALSE 参数告诉 CodeIgniter 不要用反引号 ( '
)保护生成的查询。这意味着生成的 SQL 将是:UPDATE users SET votes= votes + 1 WHERE id= '44'
如果您注意到,从 中删除了反引号'(votes+1)'
,这会产生将 votes 属性增加 1 的预期效果。
回答by wanderer
$data = array('votes' => 'votes + 1');
foreach ($data as $key=>$val) {
$this->db->set($key, $val, FALSE);
}
$this->db->where('id', $post['identifier']);
$this->db->update('users', $data);
回答by Sani Kamal
You can do as given below:
您可以按照以下说明进行操作:
public function increament_product_count(){
$product_id=$this->input->post('product_id');
$this->db->where('id', $product_id);
$this->db->set('click_count', 'click_count+1', FALSE);
$this->db->update('tbl_product');
}