Statistics and Counters Php

function Counter($page = '') {
/* this function will take $page as an arguement.
* using different values for $page will allow
* you to use a different counter on each page.
* if you want the same counter for all of your
* site then don't pass in $page */
/* connect to and select database */
mysql_connect ('localhost','username','password');
mysql_select_db ('database');
/* set expire time for ips
* 600 seconds = 10 minutes */
$expire = time() - 600;
/* delete from table where ip has expired */
$query = "DELETE FROM counter_ips " .
"WHERE viewtime < $expire " .
"AND page = '$page'";
mysql_query ($query);
/* now we check to see if the users
* ip exists in the table */
$query = "SELECT ip FROM counter_ips " .
"WHERE ip = '{$_SERVER['REMOTE_ADDR']}'" .
"AND page = '$page'";
$result = mysql_query ($query);
if (mysql_num_rows ($result) > 0) {
/* if the ip existed, update the view time */
$viewtime = time();
$query = "UPDATE counter_ips SET viewtime = '$viewtime'" .
"WHERE ip = '{$_SERVER['REMOTE_ADDR']}'" .
"AND page = '$page'";
mysql_query ($query);
} else {
/* ok time to record a hit and the ip */
/* first check if a record exists for $page */
$query = "SELECT num FROM counter " .
"WHERE page = '$page'";
$result = mysql_query ($query);
if (mysql_num_rows ($result) == 0) {
/* if no row, add one */
$query = "INSERT INTO counter VALUES " .
"(1,'$page')";
mysql_query ($query);
} else {
/* there is a row so just update it */
$query = "UPDATE counter SET num = num + 1 " .
"WHERE page = '$page'";
mysql_query ($query);
}
/* add ip to ip table */
$viewtime = time();
$query = "INSERT INTO counter_ips VALUES " .
"('{$_SERVER['REMOTE_ADDR']}', '$page', $viewtime)";
mysql_query ($query);
}
/* now we get the counter value and return it */
$query = "SELECT num FROM counter WHERE page = '$page'";
$row = mysql_fetch_assoc (mysql_query ($query));
return $row['num'];
}
/* table dumps
CREATE TABLE `counter` (
`num` int(10) unsigned NOT NULL default '0',
`page` varchar(100) default NULL,
KEY `page` (`page`)
) TYPE=MyISAM;
CREATE TABLE `counter_ips` (
`ip` varchar(16) NOT NULL default '',
`page` varchar(100) default NULL,
`viewtime` int(11) unsigned NOT NULL default '0',
KEY `ip` (`ip`),
KEY `viewtime` (`viewtime`),
KEY `page` (`page`)
) TYPE=MyISAM;
*/
?>