<?php

// Title: hitcounter_sub.php

// Author: Burton Rosenberg
// Created: 18 June 2007
// Last Update: 18 June 2007

// Copyright (c) 2007 Burton Rosenberg. All rights reserved.

$dbhost 'localhost' ;
$dbuser 'myhits' ;
$dbpass 'xxxxxxxx' ;
$dbase 'hitcounter' ;
$debug ;

$status null ;

function 
connectToDB() {

   global 
$dbpass$dbase$dbuser$dbhost ;
   global 
$status ;
   global 
$debug ;

   if ( 
$debug>) { echo "connecting to db $dbase as user $dbuser ... \n" ; }

   
$link mysql_connect($host$dbuser$dbpass ) ;
   if (!
$link) {
      
$status 'Could not connect: ' mysql_error();
      if ( 
$debug>) { echo $status "\n" ; }
      return 
null ;
   }
   if (!
mysql_select_db($dbase) ) {
      
$status 'Could not select database '.$dbase.': 'mysql_error;
      if ( 
$debug>) { echo $status "\n" ; }
      return 
null ;
   }
   if ( 
$debug>) { echo "connected!\n" ; }
   return 
$link ;
}

function 
disconnectFromDB($link) {
   global 
$debug ;
   
mysql_close($link);
   if ( 
$debug>) { echo "diconnected!\n" ; }
}

function 
checkName$name ) { 
   global 
$debug ;
   if ( 
preg_match"/\W/"$name )) { 
      if ( 
$debug>) { echo "checkName: name has illegal characters.\n" ; }
      return 
False ;
   }
   return 
True ;
}

function 
incrementHitCounter($name) {

   
$link connectToDB() ;
   if ( !
$link ) return ;
 
   
// check $name contains only alpha-numeric
   
if( !checkName($name) ) return ;

   
$query 'UPDATE hits set hits = hits+1 where name="'.$name.'";' ;
   
$result mysql_query($query) ;
   
// check return , $result should be 1

echo "Result of query |$query| is $result\n" ;

   
disconnectFromDB($link) ;
   return ;
}

function 
getHitCounter($name) {
   global 
$debug ;

   
$link connectToDB() ;
   if (!
$link ) return -;
   if ( !
checkName($name) ) return -;

   
$query 'select hits from hits where name="'.$name.'";' ;
   
$result mysql_query($query) ;
   if ( !
$result ) {
      if ( 
$debug>) { echo "Query failed:" mysql_error() . "\n" ; }
      return -
;
   }

   
$n = -;
   
// number of rows in $result should be exactly 1
   
while ($row mysql_fetch_assoc($result)) {
      
$n $row['hits'] ;
   }

   
mysql_free_result($result);
   
disconnectFromDB($link) ;
   return 
$n ;
}


?>