Many sites display their Total Hits: and Unique Hits: on their home page. This tutorial will teach you how to do that using PHP and MySQL. The Final Code can be viewed at the end of the tutorial, but it recommended that you go through the entire tutorial to understand how it works.
At the end of the tutorial you should end up with:
- MySQL table: stats
- stats.php
Before making any script, its important to lay out how your script will work.
I layed it out like this:
- Create a MySQL Table with 2 fields for storing information: IP and Number of Visits
- Count the Number of Visits
- Count the Number of Unique IP's
- Echo the Results
Now that we have done that, we are ready to begin coding.
Out first action is to create our MySQL table like we said above. Here's your query (It will be explained below).
CODE
CREATE TABLE `stats` (
`ip` VARCHAR( 15 ) NOT NULL ,
`visits` INT NOT NULL
) TYPE = MYISAM ;
If you don't understand the query, here is how it works:
- The first line is pretty obvious, it creates a table called stats.
- The second line creates a field called ip, which stores various characters (15 of them) and it cannot be blank (NOT NULL). You need to use VARCHAR because IP addresses have "." in them, and won't be recognized if you use INT (Integer). This field will be used to store the visitors IP address.
- The third line creates a field called visits that stores integers in it, and it cannot be left blank (NOT NULL). This field will be used to store how many times that IP address has visited your site.