简体   繁体   English

在CodeIgniter中一行内增加文章视图

[英]Increment article views on the fly within one row in CodeIgniter

I have a column called counter in my table called articles 我有一个在我的表称为项目 计数器称为列

The question is how can I increment the value in this column about 1, so in the controller or model I will use update db function. 问题是如何将此列中的值增加大约1,因此在控制器或模型中我将使用更新db函数。

Eg I am thinking about something like this: 我正在考虑这样的事情:

 $id = 5; //article id (I will get that from the url or db, no problem with that)
 $this->db->update("current counter column value plus one where id column equals $id "); 

And let's assume that I get the article # of views: 让我们假设我得到了一篇观点文章:

$this->db->select_sum("counter")->get("articles");

I know that I need to validate ip of the user so eg I count it not for every pageload, but only after 5 min. 我知道我需要验证用户的ip,所以我计算不是每个页面加载,而是仅在5分钟后。 But that is another story ;). 不过那是另一回事了 ;)。 I jsut need to finish this problem. 我需要完成这个问题。

You can use a regular query (with bindings): 您可以使用常规查询(带绑定):

$sql = "UPDATE articles SET counter = counter + 1 WHERE id = ?";
$this->db->query($sql, array($id));

Or, using the AR: 或者,使用AR:

$query = $this->db->update('articles')
                   ->set('counter','counter+1', FALSE)
                   ->where('id', $id);

The FALSE as the third argument in set() tells it not to escape the column names. FALSE作为set()的第三个参数告诉它不要转义列名。
You don't need to get the number of views if you only need to increment. 如果只需要增加,则无需获取视图数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM