Page 1 of 1

MySQL page counter

Posted: Sat May 17, 2008 5:26 pm
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?

Re: MySQL page counter

Posted: Mon May 19, 2008 1:54 pm
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";

Re: MySQL page counter

Posted: Tue May 20, 2008 7:04 am
by dramiditis
Thank you .