29
Apr
09

[PHP] Hit Counter using MySQL Database

Little script I wrote this morning which uses a database to store number of hits on a page:

<?php
	$dbhost = '1';
	$dbuser = '2';
	$dbpass = '3';
	$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('0');
	$dbname = '4';
	mysql_select_db($dbname);

	$page = $_SERVER['REQUEST_URI'];
	$result = mysql_query("SELECT HIT_COUNT FROM  Hit_Count WHERE Page_Name = '$page'");

	$any = false;
	while($row = mysql_fetch_array($result)) {
		$any = true;
		$counter = mysql_result($result, 0) + 1;
		$sql = "UPDATE Hit_Count SET HIT_COUNT = '$counter' WHERE Page_Name = '$page'";
		mysql_query($sql);
		echo($counter);
	}

	if($any == false) {
		$sql = "INSERT INTO Hit_Count (Page_Name, HIT_COUNT) VALUES ('$page', '1')";
		mysql_query($sql);
		echo("1");
	}

	mysql_close($conn);
?>

The script will output the current hit count, you would use the script like this:

<?php include("location/hitcount.php"); ?>

The tables set up is this:

Page_Name [text]		HIT_COUNT [int(11)]
/files/Image%20Gallery.php 	2
/ 				4
Advertisements

0 Responses to “[PHP] Hit Counter using MySQL Database”



  1. Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: