Simple ip counter based on PHP & mysql

PHP, Programing Add comments

Learn how to make a simple ip counter for your website using PHP programing language and Mysql database.
In this tutorial you will learn how to make the tables on mysql database and how to program with examples the counter script.

1. Make a mysql database from your cpanel hosting. If you don`t know how to do that, tipe in the searchbox "how to create a mysql database"
2. Create the mysql tables in the database:

id This is the id of the counter and will be unique to each counter you may start..

count This is the actual number of times the page has been loaded..

3. Whe will make our script to automaticaly create the tables in your database:
Create a php file called "setup.php" and insert this code:

PHP:
  1. <?
  2. $dbh = mysql_connect(localhost,DBUSER,DBPASS) or die("Cannot connect database");
  3. mysql_select_db(DATABASE) or die( "Unable to select database");
  4.  
  5. mysql_query("CREATE TABLE counter (id INT NOT NULL AUTO_INCREMENT,
  6. PRIMARY KEY(id),
  7. count VARCHAR(30)NOT NULL)")
  8. mysql_query("INSERT INTO counter
  9. (count) VALUES('0') ")
  10. or die(mysql_error()); ?>
  11. echo "<p align=center><b><font face=Verdana size=4>Counter database successfully created..";
  12. ?>

Modify "dbuser" & "dbpass" with your mysql database settings.
Note: Localhost is used in almost 90% case by the hosting companies, but depends. Read carefuly in your cpanel hosting or the hosting website.

4. Create the php file called "count.php" and paste this code:

PHP:
  1. <?
  2. $dbh = mysql_connect(localhost,DBUSER,DBPASS) or die("Cannot connect database");
  3. mysql_select_db(DATABASE) or die( "Unable to select database");
  4. $sql = "SELECT id, count, url, FROM counter WHERE id = 1";
  5. $result = mysql_query($sql);
  6. if (!$result)
  7. {
  8. echo 'Error with the query. Message returned: ' .
  9. }
  10. while ($row = mysql_fetch_assoc($result))
  11.  
  12. $count = $row['count']+1;
  13.  
  14.  
  15. $query = "UPDATE counter SET count = '$count' WHERE id = 1";
  16. mysql_query($query);
  17.  
  18.  
  19. echo "$count";

Modify again the database username and password.

5. Upload all files in your web server with a ftp client and run the php file called "setup.php" to create the tables in your mysql database.
6. Now we can simply include it in any PHP file with the PHP include like:

Leave a Reply

WP Theme & Icons by N.Design Studio
Entries RSS Comments RSS Log in