Simple Web Page Hit Counter Code Using PHP and MySQL

Digital display of numbers

Sinenkiy/Getty Images

Website stats provide important information to a website owner about how the site is doing and how many people visit. A hit counter counts and displays how many people visit a webpage.

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 webpage using PHP and MySQL. The counter stores the hit totals in a MySQL database.

The Code 

To get started, create a table to hold the counter statistics. Do that by executing this code:

CREATE TABLE `counter` ( `counter` INT( 20 ) NOT NULL );

The code creates a database table named 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 the count increases by one each time the file is called. Then the new number is displayed. This process is accomplished with this PHP code:

// Connects to your Database
mysql_connect("", "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]";

This simple hit counter doesn't give the website owner valuable information such as whether the visitor is a repeat visitor or a first-time visitor, the location of the visitor, which page was visited, or how much time the visitor spent on the page. For that, a more sophisticated analytics program is necessary.

Counter Code Tips

Wanting to know the number of people who visit your site makes sense. When you are comfortable with the simple counter code, you can personalize the code in several ways to work better with your website and gather the information you seek.

  • 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
mla apa chicago
Your Citation
Bradley, Angela. "Simple Web Page Hit Counter Code Using PHP and MySQL." ThoughtCo, Aug. 27, 2020, Bradley, Angela. (2020, August 27). Simple Web Page Hit Counter Code Using PHP and MySQL. Retrieved from Bradley, Angela. "Simple Web Page Hit Counter Code Using PHP and MySQL." ThoughtCo. (accessed May 29, 2023).