问题
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