on Sat Jul 05 08:36:50 GMT 2008 in PHP and viewed 2587 times
Statistics is something that can be very useful to any website, telling how many visits you have, how many are different people, and so on. This tutorial will tell how to do all of that with a MySQL database.
This is a fairly simple tutorial that requires no more than a mysql database, and a bit of PHP and MySQL knowledge. To start, here’s the basic outline for your “counter” table.
CREATE TABLE counter ( id int PRIMARY KEY NOT NULL auto_increment, ip text NOT NULL) TYPE=MyISAM
What this basically does is create a table called “counter” with 2 fields: a basic identification field that will go up by one with every row entered, and an ip field, as to identify unique hits. The overall code for the application is thus:
<?php
$connection = mysql_connect("localhost", "username", "password");
mysql_select_db("dbname", $connection);
//finished connecting to the mysql db
$ip = $_SERVER[REMOTE_ADDR];//gets the visitors IP address
$insert2 = "INSERT INTO counter VALUES ('', '$ip')";
mysql_query($insert2) or die(mysql_error());
//inserts the value into the table. The id is left empty because it will automatically update, and the ip is entered for the second field.
$select = "SELECT * FROM counter";
$stuff = mysql_query($select) or die(mysql_error());
//this will select the number of total hits from the database
//we just select all because all we will do, is a numrows query
$numrows = mysql_num_rows($stuff);
echo "Total Hits: $numrows<br> Your IP is $ip.<br>";
$uniques = "SELECT DISTINCT ip FROM counter";
$query = mysql_query($uniques) or die(mysql_error());
//the difference here, is that we're selecting DISTINCT ips from the table
//the "DISTINCT ip" tells the script to only select unique ip rows, so the mysql_num_rows will only number the unique hits
$numrows2 = mysql_num_rows($query);
echo "Unique Hits: $numrows2<br><br>";
?>
Ok, first is the connection process. You can figure that out. Next it defines $ip as the visitor’s ip. Isn’t that cool? Well if you don’t think so, you really need to re-evaluate your life. Ok, next is the insert process. We simply insert the values. First is the count, the id, then the ip. Easy as that. Right after that we select everything from the counter.
Then we just use numrows() to figure out how many rows there are in all. That shows us how many hits there are overall. Then there’s the second select. The DISTINCT thing is what makes it cool. It counts all of the hits that are different from each other. Then I simply out put it all with some echo statements.