Google it! / Yahoo it! / Bing it! / Ask it!

article-counter-tutorial

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):

CREATE TABLE `counter` (
`counter` int(9) NOT NULL default '0'
) TYPE=MyISAM;

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

<?php
// 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 include('/phpmysql_counter_tutorial/counter.html');?>

2 Responses to PHP/MySQL Counter Tutorial

Leave a Reply

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

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>