As we mentioned in our previous post, the MaxMind geoip database doesn’t do too well with getting the zip code of users that visit your sites. We had a use today to grab the zipcode and popular an area of our site with it, and we’re going to show you how to do it as well.

This assumes you already have GEOIP working, and are using the standard free database, and our zipcode database tutorial.

First, create a database connection script to call from your existing GEOIP page. We called ours opendb.php, and it contains this;

<?php  
$dbhost = 'localhost';  
$dbuser = 'databaseusername';  
$dbpass = 'databasepassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
$dbname = 'databasename';  
mysql_select_db($dbname);  
?>

Then we went ahead and added this to our landing page with the geoip code in it;

include("opendb.php");

Following that, we added this block of code.

// for zip code  
$query = "SELECT zipcode FROM zipcodes WHERE town = '$usercity' and state = '$userstate' LIMIT 1";  
// echo $query;  
$result = mysql_query($query);

while($row = mysql_fetch_row($result))  
{  
$zipcode = $row[0];  
//echo "Zipcode: $zipcode <br>";  
}  
mysql_free_result($result);

What this does, is use the GEOIP features to determine the visitors state, and city. Then it looks that information up against our zipcode database, and returns the closest zipcode to them.

You can then echo the zipcode easily like this;

<?php echo $zipcode; ?>

Voila!

Note that this probably isn’t the best code, and almost certainly has bugs (like if no zip code exists, or it might pick a wrong zipcode), but it’s better than nothing, and in our testing has worked 100% of the time so far, ymmv though.

Comments

Comment by Trey on 2009-09-28 05:32:58 -0500

Hello, I am trying to follow your geo ip zip code tutorial, but I am not able to figure out what you mean by “existing GEOIP page”

I searched maxmind and cannot find any info on how to create a geoip page or if they have and templates I can use.

I can’t figure out what goes on the landing page.

Above you have a code start with “// for zip code” but what code is around this?

If you could direct me to where I need to go and what I need to do, it would be greatly appreciated. Thanks

Comment by Matt G on 2009-09-28 19:12:58 -0500

Hey Trey,

Thanks for reading.

Your “Existing GEOIP Page” would be your landing page if you followed the previous tutorial on getting GEOIP setup.

You’ll just need the free geoip database, and the template code they have on maxminds site. I think I linked it from the initial post, if not let me know and I can try and find it for you, or post up a zip file.