view counter code

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
irshad_sheikh
Forum Newbie
Posts: 7
Joined: Mon Jan 19, 2009 1:57 am

view counter code

Post by irshad_sheikh »

Hello,

Am I on the right track to create code for view counter in php?
I am using codeIgniter framework.
My code is:

Code: Select all

 
function update_view_count($topic_id)
         {
            $count = 0;
                $query = "SELECT viewcount FROM forum_topics WHERE id = '".$topic_id."'";
                $temp=$this->db->query($query);
                foreach($temp->result() as $value)
                  {
                      $count = $value->viewcount;
                  }
                $count = $count + 1;
 
                $query="UPDATE forum_topics SET viewcount = $count WHERE id=$topic_id";
                $temp = $this->db->query($query);
                return $count;
        }
 
or is there any other way?
Last edited by Benjamin on Fri May 08, 2009 9:38 am, edited 1 time in total.
Reason: Changed code type from text to php.
ben.artiss
Forum Contributor
Posts: 116
Joined: Fri Jan 23, 2009 3:04 pm

Re: view counter code

Post by ben.artiss »

Hi, MySQL can increment a hit counter for you:

Code: Select all

mysql_query("UPDATE forum_topics SET viewcount=viewcount+1 WHERE id=$topic_id")
It's also faster than letting PHP calculate the new number of hits - hope that helps.
Post Reply