MySQL page counter

Questions about the MySQL, PostgreSQL, and most other databases, as well as using it with PHP can be asked here.

Moderator: General Moderators

Post Reply
dramiditis
Forum Newbie
Posts: 13
Joined: Tue Jan 22, 2008 7:23 am

MySQL page counter

Post by dramiditis »

Hi there, my page path are " /watch.php?v= " and I would like to count page hits for every page from 0, I mean every page will have different page views .
I can't figure php sintax and table rows for this.
Can anyone help me?
User avatar
Jade
Forum Regular
Posts: 908
Joined: Sun Dec 29, 2002 5:40 pm
Location: VA

Re: MySQL page counter

Post by Jade »

The idea behind this is pretty basic.

You'll need a table that keeps at least 2 fields. One field is for the name of the page, and the other field is for the hit counter. Every time someone loads a page you'll need to:

1) check if that page is already in the table

2) if that page is found increase the value in the counter field

3) if that page isn't found, add it to the database and increase the counter field

Your sql table will look something like this:

Code: Select all

 
CREATE TABLE hitcounter (url varchar(255) PRIMARY KEY, hits int);
 
Your code will look something like this and you'd put it at the top of every page

Code: Select all

 
<?php
$file = $_SERVER['PHP_SELF'];
 
$result = mysql_query("SELECT hits FROM hitcounter WHERE url='$file'")
or die ('cannot select hits from hit counter: '  . mysql_error());
 
$exists = mysql_num_rows($result);
 
if ($exists) //there is a row in the table for this page
    mysql_query("UPDATE hitcounter SET hits=hits+1 WHERE url='$file'")
    or die ('cannot update hit counter for this page: ' . mysql_error());
 
else //there is no row in the table for this
    mysql_query("INSERT INTO hitcounter (url, hits) VALUES ('$file', 1)")
    or die ('cannot add new page to the hit counter: ' . mysql_error());
?>
 
Then, if you wanted to display the hits you'd do something like this:

<?php
$file = $_SERVER['PHP_SELF'];

$result = mysql_query("SELECT hits FROM hitcounter WHERE url='$file'")
or die ('cannot select hits from hit counter: ' . mysql_error());

$row = mysql_num_rows($result);
echo $row['hits'] . " hits on this page";
dramiditis
Forum Newbie
Posts: 13
Joined: Tue Jan 22, 2008 7:23 am

Re: MySQL page counter

Post by dramiditis »

Thank you .
Post Reply