So you want to keep track of your website hits in a database. Using the following code this is possible. Lets start.
Create a blank database on your server. Now using a database manager like phpmyadmin, add the following sql into the database:
CREATE TABLE `hit_count` (
`hits` int(50) NOT NULL default ‘0′
) TYPE=MyISAM;INSERT INTO `hit_count` VALUES (0);
Next create a blank document on your computer using your favorite editor and past the following into that file:
// DB Settings $server = 'localhost'; $user = ''; $pass = ''; $db2 = ''; $db = mysql_connect("$server", "$user", "$pass") or die("Could not connect."); if(!$db) die("no db"); if(!mysql_select_db("$db2",$db)) die("No database selected.");
Add your username to MySQL between the ‘ ‘ in the $user = ”;.
Add your password to MySQL to the $pass and your database name to the $db2.
Now after:
die("No database selected.");But before:
?>Add the following code:
$query1 = mysql_query("SELECT hits FROM hit_count");// Get hit count
$total = mysql_fetch_array($query1);
$hitCount = $total['hits'] + 1;// Add 1 to the count
$sql = "UPDATE `hit_count` SET `hits` = '$hitCount'"; // Update Hits
mysql_query($sql) or die("Unable to process query: " . mysql_error());
echo 'Hits: '.$hitCount; // Show hitsThats all there is to creating a hit counter and showing the results on your page.
If you want to show the hits on a page without updating them you can use the following code:
$total = mysql_fetch_array($query); echo 'Total Hits: '.$total['hits'];
Make sure that you connect to the database before you call the above code.




















(3 votes, average: 4.00 out of 5)
August 23rd, 2009 at 5:31 pm
In the name of Allah, the Most Gracious, the Most merciful…
thanks a lot Mr. Daniel I have benefited from this article.
Barham, Iraq-Kurdistan.