Counter and Hits With MySQL

Below is the script on how to make visitor's counter based on Mysql database

create table on your database:

CREATE TABLE `counter` ( 
   `count_id` varchar (225) NOT NULL default'', 
   `count` longtext NOT NULL, 
   `hits` longtext NOT NULL 
) TYPE = MyISAM; 

notes: 
for initial value for:
"count_id" enter the value 1 
"count"  enter the value 1 
"hits" enter the value 1 

below is the script for counter: 
<?php
session_start();
/* Database connection ----- begin ------- */
$dbhost = 'localhost'; /* your host ----- ------- */
$dbusername = 'username'; /* your user ----- ------- */
$dbpasswd = 'password'; /* your password ----- ------- */
$database_name = 'database'; /* your database name ----- ------- */

/* ----- Start db connection, code below do not change in ------- */
$connection = mysql_pconnect("$dbhost", "$dbusername", "$dbpasswd") or die ( "Could not connect to server.");
$db = mysql_select_db("$database_name", $connection) or die ( "Could not select database.");

/* Database connection out ----- ------- */

//  ----- If session "counted" has not been listed ------- *
if (!session_is_registered("counted")) {

/* ----- Update the cell "count" to add a +1 ------- */
mysql_query("UPDATE counter SET count = (count + 1) WHERE count_id = 1");

/* ----- Register session "counted" ------- */
session_register("counted");
}
?>

//script for visitor:
/* ----- Show value / value from the table "counter" column to the 2-I mean the "count" ------- */
$sql = mysql_query ("SELECT * FROM counter limit 1");
while ($row = mysql_fetch_array ($sql)) {
echo $row [1];
}
?>

script for hits:
<?php
/* ----- For the hits, we do not need the function "IF" ------- */
// Update cell ----- "hits" to add a +1 ------- */
mysql_query("UPDATE counter SET hits = (hits + 1) WHERE count_id = 1");

/* ----- Show value / value from the table "counter" column to the 3-I mean the "hits" ------- */
/* ----- Who has been in the process of update of the above ------- */
$sql = mysql_query ("SELECT * FROM counter limit 1");
while ($row = mysql_fetch_array($sql)) {
echo $row [2];
}
?>

No comments: