ranking Sort Sort   |   date Sort Sort   |   member Sort Sort
Syndication

23
Date Submitted Tue. Oct. 24th, 2006 8:13 PM
Revision 1
Helper dohpaz
Tags mysql | mysqli | PHP
Comments 4 comments
If you've ever wanted to build an application that can both find the distance between two zip codes, and find zip codes within a specific radius of another zip code, then this is the snippet for you.

I've tried to build this before using PHP4 and MySQL 4 and have found it to be painfully slow for a one-user connection over a Local Area Network (LAN). So, before you continue reading, I must make it abundantly clear that this method requires PHP 5 and MySQL 5.

This is because in PHP5, we will need the MySQL-Improved interfaces, and in MySQL 5, we will need functions and procedures.

Using functions and procedures in MySQL puts the weight of the calculations on MySQL, where they will run hundreds of times faster than if PHP were to attempt to do the work. In addition, using functions and procedures is still hundreds of times faster than carefully crafted SQL statements (one benchmark took over 10 seconds using a WHERE clause, while the function + procedure method took around .12 seconds--note the dot).

Since I am not a mathematician by trade, I found the necessary calculations using Google.

For the "Great Circle Distance" formula, I used Meridian Word Data's website. For the radius finder, I used another that unfortunately I do not have off the top of my head right now. I will look for it again and repost it for proper accreditation.

For the zip code database, I am using the free zip code database from CFDynamics.

Below, you will find the database and table schema, the functions and procedures, and also a demo PHP script to see all of this put into action. As a courtesy, you may download a dump of this database from my website. It's uncompressed size is 3.4M, and it's compressed size is 537K. The checksum is available here.

Please leave me comments, suggestions, questions, and/or rants about this snippet. I feel this is a very useful bit of code, and hope that others out there may find as much use from it as I will be.