aspirinemaga
aspirinemaga

Reputation: 3937

Codeigniter update a column in a database while retrieving with activerecords

I'am learning to make a blog in CodeIgniter 2.x . What I want - when user clicks on the link readmore on the blog's page, it will redirect him to the page with corresponding id to show him a full article.

Now, while retrieving a $query->row(); from a database in content_model.php, i want to update a viewed column in database at the same time. So instead of showing him for example 34 views, it will show 35 views, and when someone open the same link it will shows him by one more - 36 views.

What's the best way to do it without making it vulnerable to hackers somehow ?

Thank you in advance for any help.

Upvotes: 0

Views: 178

Answers (2)

Fad
Fad

Reputation: 9858

This should be very easy. When someone tries to read a post, just before you retrieve the post information, update the count views in the database. Execute a query that goes something like this

UPDATE `posts` SET `views` = `views` + 1;

After that, simply retrieve the post information just like you normally would, and then show it to the user by outputting it to the browser.

Upvotes: 1

Jubayer Shamshed
Jubayer Shamshed

Reputation: 48

When you retrieving data from database using CI framework, you check this following:

    if ($result_from_get_function->num_rows()>0){
    return   $this->updateViewColoumnByOne();
    }else{
    return false;
    }
    function updateViewColoumnByOne(){
    //retrieve number of view in view column, suppose 12.
    //plus one with it; 12+1=13
   //update it.
   //again retrieve the new update number of views
   //and return.
   }

I think this could help you.

Upvotes: 1

Related Questions