Search code examples
phpmysqlianalyticshitcounter

PHP page hit counters in database


I run a podcast network and I'm redoing my site from scratch. One of the features on my network is to listen to podcasts directly from the site in an HTML5 player. I have all that functionality working just fine, but I'd like some analytical data on those pages.

I'd like to make a hit counter in PHP and store it in a DB table. But, there's only one page. The player loads each show, dependent on the query string, then it pulls the latest episode from their RSS Feed, like so: http://tangentboundnetwork.com/new/show.php?id=1

I want to be able to put analytical data into a table and use it for the hosts of whatever show(s) are on the network.

I just need to know where to start. Any ideas, Links, and examples would be welcome.


Solution

  • First, create your database table VISITOR_COUNT. You will need at least two columns - SHOW_ID and COUNT.

    The code in show.php could look something like this:

    • If you want to count unique (or sort of unique - you can never be completely sure) visitors, check if a specific cookie for the current $id is set. Read more about cookies in PHP here.
    • If the cookie is not set:
      • Set the cookie.
      • Check if there is a row in VISITOR_COUNT with SHOW_ID = :id where :id is the value of $id. Watch out for SQL injection!
      • If there is, run some SQL to update it: UPDATE VISITOR_COUNT SET COUNT = COUNT + 1 WHERE SHOW_ID = :id
      • If not, insert a row with the right ID and a count value of 1.