getButterfly Logo getButterfly

One of my clients required a simple text counter to show pageloads. Not very realistic, but the web site was not in danger of refreshing just to increase pageloads. So here it is. It uses PHP and MySQL.

First of all, create a new table in your database (suppose the web site already has a database):

[text]CREATE TABLE `counter` (
`counter` int(9) NOT NULL default ‘0’
) TYPE=MyISAM;[/text]

With the table in place, we can create the actual counter.php file.

// Simple PHP/MySQL counter
// Database details and connection
$host = “localhost”; // Database host name (usually ‘localhost’)
$username = “dbroot”; // MySQL username
$password = “dbpass”; // Mysql password
$dbname = “dbname”; // Database name
$tblname = “counter”; // Table name
mysql_connect(“$host”, “$username”, “$password”) or die(“Error: Unable to connect.”);
mysql_select_db(“$dbname”)or die(“Error: Unable to select database.”)
$sql = “SELECT * FROM $tblname”;
$result = mysql_query($sql);
$rows = mysql_fetch_array($result);
$counter = $rows[‘counter’];
// If counter value is 0 set is to 1
if(empty($counter)) {
$counter = 1;
$sql1 = “INSERT INTO $tblname(counter) VALUES(‘$counter’)”;
$result1 = mysql_query($sql1);
echo $counter.’ visitors so far.’;
// Increment value
$addcounter = $counter+1;
$sql2 = “UPDATE $tblname SET counter=’$addcounter'”;
$result2 = mysql_query($sql2);

Now, the file is ready for inclusion in the web site footer file:

[php]<?php include(‘counter.php’);?>[/php]

Subscribe to getButterfly Blog

Once a week or so we send an email with our best content. We never bug you, we just send you our latest piece of content.

If you found any value in this post, agree, disagree, or have anything to add - please do. I use comments as my #1 signal for what to write about. Read our comment policy before commenting! Comments such as "Thank you!", "Awesome!", "You're the man!" are either marked as spam or stripped from URL.

Leave a Reply

Your email address will not be published. Required fields are marked *