Tips, tricks, tutorials…

PHP – MySQL visitor counter

In this tutorial I’m going to describe how to increment a view counter in a MySQL database. We are going to use PHP with the most simple solution. We want to keep this very simple so we won’t track IP addresses and won’t use cookies to avoid one visitor being counted multiple times. So basically this will be a page load counter, not an individual user counter.

Prepare the MySQL database tables

First we have to create the database tables or add the columns to an existing one to store the information.

Connect with phpMyadmin and open the existing database you want to work with. Click Structure / Add 1 column and click Go. Let the column name be ‘visits’, INT type, length 15, Default 0 (so we can start counting from 0). Leave the remaining fields untouched and hit the Save button.

If you don’t have an existing database, create one with an ‘id’ (int, AUTO_INCREMENT, key) field and the ‘visits’ mentioned above

The PHP code

First we have to connect to the database.

We need two queries. The first one increases the value of the counter, where the id is associated to the specific page. We need to adjust the id for each page, or we can use a PageName/URL column for that according to our needs:

UPDATE Counter SET visits = visits+1 WHERE id=1

The following query retreives the value and stores it in a variable. This will be later displayed in the HTML body seciton.