Tyiny error in referrer code, help

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
mikusan
Forum Contributor
Posts: 247
Joined: Thu May 01, 2003 1:48 pm

Tyiny error in referrer code, help

Post 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']}' )");
		}
	}
?>
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Post 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']}' )"); 
      } 
}
User avatar
mikusan
Forum Contributor
Posts: 247
Joined: Thu May 01, 2003 1:48 pm

Post 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.
Post Reply