General Statistics
390 Tutorials
202 Total Votes
11 User(s) Online
747209 Views Total
3000 Registered Members
24435 Posts Total
Rooneyfeld is our newest member
About this Tutorial: Display Total and Unique Hits on Your Site
Display Total and Unique Hits on Your Site
Rated 5 / 4 Votes

Display Total and Unique Hits on Your Site

Learn how to display the total number of visits and total number of unique visits to your site using PHP and MySQL.


Date Added: December 24, 2005 [ 11673 Views - 4 Votes ] [ Rate ]

Author: Boost [ PHP Coding ] [ 10 Comment(s) ]

Display Total and Unique Hits on Your Site
Our first task will be inserting the visitors IP into our MySQL Table. PHP has a handy built in code called $_SERVER['REMOTE_ADDR'] that will take the get the visitors IP address. We can use that code and store it into a variable to insert into our Database. The following code does that:
CODE
$ip = $_SERVER['REMOTE_ADDR'];

Now comes the magic. Once we have the visitors IP we need to check our table if the visitor has already visited your site or not. We can use an If/Else statement to do this very easily.
CODE
$fetch = mysql_query("SELECT ip FROM $tbl_name WHERE ip ='".$ip."'") or die(mysql_error());

if ( mysql_num_rows($fetch) == 0 ) {
   mysql_query("INSERT INTO $tbl_name(ip,visits) VALUES('$ip','1')") or die(mysql_error());
} else {
   mysql_query("UPDATE $tbl_name SET visits=visits+1 WHERE ip = '$ip'") or die(mysql_error());
}

$fetch is suppose to select the row of our MySQL table that contains the IP address of our visitor. If $fetch equals 0, that means that the visitor has never visited your site before, because a row for his IP address and number of visits doesn't exist. In that case, we must insert the new visitors IP Address into the IP row of our table, and in the visits row of our table.

If the users IP was found already (meaning he has already visited the site at least once), all we need to do is add one to our visits row, next to his IP address. Our else statement does exactly that.

All that is left now is outputting our results!

Total Pages (4)
<<Prev 1 2 [3] 4 Next>>

Welcome User
Welcome Guest
( Login | Register )

Latest Tutorial Index - RSS Feed
Latest Resources - RSS Feed
Latest Tutorials - RSS Feed
Vote for Us
  • VixxIMG.com - Free Image Hosting, Free Myspace Image Hosting, Free Image Uploads
  • PageRank Plus - Google PageRank checking, with a twist.
Random Affilaites