In PHP, I have the following code for calculating the distance between two locations:
MySQL has the ability to index rows geospatially. You might not need to do this math by yourself (you can just ask MySQL to compute the distance between two geo objects and sort by that..).
See: http://forums.mysql.com/read.php?23,159205,159205