...

View Full Version : I've made a Counter, help to improve it!



maltrecho
09-18-2003, 11:14 PM
The problem when you want to count unique visitors is that you'll have to store all the ips somewhere (I don't want to use cookies for this). This counter will store ips just for one day and it will also store the unique visitors for each day (presuming you've got a min of 1 visit [you] and a max of 9999). could you help me to improve it?

BEFORE RUNNING THE CODE CREATE A DATABASE LIKE THE FOLLOWING:
"CREATE DATABASE `counter`";
AND CREATE THE FOLLOWING TABLE IN THAT DATABASE
"CREATE TABLE `stats` (`date` varchar(10) NOT NULL default '',`total` smallint(4) NOT NULL default '0') TYPE=MyISAM";


<?php

//CONNECT TO SERVER, SELECT DATABASE AND GET DATES & USER IP//

$server = "localhost";
$user = "";
$password = "";
$database = "counter";

$connect = mysql_connect($server, $user, $password);
$db = mysql_select_db($database, $connect);

$today = date("d_m_Y");
$yesterday = date("d_m_Y",time()-24*3600);

$user_ip = getenv("REMOTE_ADDR");

//CHECK IF TABLE OF IPs EXISTS FOR TODAY//

$query_1 = "SHOW TABLES LIKE '$today'";
$result_query_1 = mysql_query($query_1, $connect);
$num_results_1 = mysql_num_rows($result_query_1);

//IF DOESnt EXIST (MEANS ALSO ROW IN TABLE COUNTER FOR TODAY DOESnt EXIST NEITHER)//
//DROP TABLE FROM YESTERDAY, CREATE TABLE FOR TODAY AND CREATE ROW IN TABLE COUNTER FOR TODAY//

if ($num_results_1 == '0') {

$query_2 = "DROP TABLE IF EXISTS `$yesterday`";
$result_query_2 = mysql_query($query_2, $connect);

$query_3 = "CREATE TABLE `$today` (`ip` varchar(16) NOT NULL default '',PRIMARY KEY (`ip`)) TYPE=MyISAM";
$result_query_3 = mysql_query($query_3, $connect);

$query_4 = "INSERT INTO `stats` (date,total) VALUES ('$today','0')";
$result_query_4 = mysql_query($query_4, $connect);
}

//CHECK IF USER IP ALREADY EXISTS IN TABLE FOR TODAY//

$query_5 = "SELECT COUNT(*) FROM `$today` WHERE (ip = '$user_ip')";
$result_query_5 = mysql_query($query_5, $connect);
$field_5 = mysql_fetch_array($result_query_5);
$num_results_5 = $field_5['COUNT(*)'];

//IF DOESnt EXIST INSERT NEW IP AND UPDATE COUNTER FOR TODAY//

if ($num_results_5 == '0') {

$query_6 = "INSERT INTO `$today` (ip) VALUES ('$user_ip')";
$result_query_6 = mysql_query($query_6, $connect);

$query_7 = "UPDATE `stats` SET total=(total+1) WHERE (date = '$today')";
$result_query_7 = mysql_query($query_7, $connect);
}

mysql_close($connect);

?>

:thumbsup:



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum