简体   繁体   中英

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.

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. 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:

$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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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