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?
MySQL page counter
Moderator: General Moderators
Re: MySQL page counter
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:
Your code will look something like this and you'd put it at the top of every page
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";
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);
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());
?>
<?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
Thank you .