Increment article views on the fly within one row in CodeIgniter

只愿长相守 提交于 2019-12-08 10:42:21

问题


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.

E.g. 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 e.g. I count it not for every pageload, but only after 5 min. But that is another story ;). I jsut need to finish this problem.


回答1:


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:

$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.
You don't need to get the number of views if you only need to increment.



来源:https://stackoverflow.com/questions/13939333/increment-article-views-on-the-fly-within-one-row-in-codeigniter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!