Page 1 of 1

Tyiny error in referrer code, help

Posted: Wed Nov 26, 2003 9:45 pm
by mikusan
Hi, i have a small piece of code that has an error in it, i have been staring at this for far too long and i honeslty cannot see why it is doing the following.

My database is supposed to record a referrer and if it's already there it will add the count to it. I have another function that is less sensitive and will add more functionality so that referrers with a similar domain will be counted as one, however, i cannot get the easy part to work, i keep getting individual entries of the same thing:

[referrer] [count]
http://www.php.net 1
http://www.php.net 1
...

Code: Select all

if (!empty($_SERVER['HTTP_REFERER']))
	{
		$SQL = mysql_query("SELECT * FROM am_referrer WHERE referrer='{$_SERVER['HTTP_REFERER']}");
		
		if ( $query = mysql_query($SQL) )	{
			$numrows = mysql_num_rows($query);
			if ($numrows > 0)  {
				$Data = mysql_fetch_array($query);
				$count = $Data['count'] + 1;
				mysql_query("UPDATE am_referrer SET count='$count' WHERE referrer='{$_SERVER['HTTP_REFERER']}'");
			}
		}
		else	{
		mysql_query("INSERT INTO am_referrer ( referrer ) VALUES ( '{$_SERVER['HTTP_REFERER']}' )");
		}
	}
?>

Posted: Thu Nov 27, 2003 6:29 am
by Weirdan
You missed closing single quote at this line:

Code: Select all

$SQL = mysql_query("SELECT * FROM am_referrer WHERE referrer='{$_SERVER['HTTP_REFERER']}");
Should be:

Code: Select all

$SQL = mysql_query("SELECT * FROM am_referrer WHERE referrer='{$_SERVER['HTTP_REFERER']}'");
Also you can simplify your code:

Code: Select all

if (!empty($_SERVER['HTTP_REFERER'])) 
{ 
      $query=mysql_query("UPDATE am_referrer SET count=count+1 WHERE referrer='{$_SERVER['HTTP_REFERER']}'"); 
      if ( $query)   { 
         $numrows = mysql_affected_rows($query); 
         if ($numrows == 0)   
              mysql_query("INSERT INTO am_referrer ( referrer ) VALUES ( '{$_SERVER['HTTP_REFERER']}' )"); 
      } 
}

Posted: Thu Nov 27, 2003 9:45 am
by mikusan
Terrific!!

Thank you very much... i spent so much time staring at this guy. This is a lesson for myself and anyone else out there... when your code gets longer than 1000 lines, vim just doesn't cut it anymore :)

Thanks again Weirdan.