Web Page Hit Counter

Simple Website Hit Counter Code Using PHP and MySQL

Every website owner knows that website stats provide important information about how the website is doing and how many people visit the website. A hit counter counts and displays how many people visit the web page.

The code for a counter varies depending on the programming language used and the amount of information you want the counter to collect. If you, like many website owners, use PHP and MySQL with your website, you can generate a simple hit counter for your web page using PHP and MySQL.

The counter stores the hit totals in a MySQL database. To get started, you need to first create a table to hold the counter statistics. Do that by executing this code:

 CREATE TABLE `counter` ( `counter` INT( 20 ) NOT NULL );
 INSERT INTO counter VALUES (0); 

This creates a database table "counter" with a single field also called "counter," which stores the number of hits the site receives. It is set to start at 1, and one is added each time the file is called. Then the new number is displayed. That is done with this PHP code:

 <?php
 // Connects to your Database 
 mysql_connect("your.hostaddress.com", "username", "password") or die(mysql_error()); 
 mysql_select_db("Database_Name") or die(mysql_error()); 

//Adds one to the counter

mysql_query("UPDATE counter SET counter = counter + 1");

//Retrieves the current count

$count = mysql_fetch_row(mysql_query("SELECT counter FROM counter"));

//Displays the count on your site

print "$count[0]";

?>

Counter Code Tips

  • Customize the database, table and code to include other information
  • Hold the counter in a separate file and retrieve it using include ()
  • Format the counter text using regular HTML around the include function
  • Create different rows on the counter table for additional pages on your website
    Format
    mla apa chicago
    Your Citation
    Bradley, Angela. "Web Page Hit Counter." ThoughtCo, Nov. 27, 2016, thoughtco.com/web-page-hit-counter-2693831. Bradley, Angela. (2016, November 27). Web Page Hit Counter. Retrieved from https://www.thoughtco.com/web-page-hit-counter-2693831 Bradley, Angela. "Web Page Hit Counter." ThoughtCo. https://www.thoughtco.com/web-page-hit-counter-2693831 (accessed January 21, 2018).