title: Sorting MySQL query by Latitude/Longitude
body: <p>Every user in my database has their latitude and longitude stored in two fields (lat, lon)</p>
  
  <p>The format of each field is:</p>
  
  <pre><code>lon | -1.403976 
  lat | 53.428691
  </code></pre>
  
  <p>If a user searches for other users within, say 100 miles, I perform the following in order to calculate the appropriate lat/lon range ($lat and $lon are the current users values)</p>
  
  <pre><code>$R = 3960;  // earth's mean radius
  $rad = '100';
  // first-cut bounding box (in degrees)
  $maxLat = $lat + rad2deg($rad/$R);
  $minLat = $lat - rad2deg($rad/$R);
  // compensate for degrees longitude getting smaller with increasing latitude
  $maxLon = $lon + rad2deg($rad/$R/cos(deg2rad($lat)));
  $minLon = $lon - rad2deg($rad/$R/cos(deg2rad($lat)));
  
  $maxLat=number_format((float)$maxLat, 6, '.', '');
  $minLat=number_format((float)$minLat, 6, '.', '');
  $maxLon=number_format((float)$maxLon, 6, '.', '');
  $minLon=number_format((float)$minLon, 6, '.', '');
  </code></pre>
  
  <p>I can then perform a query such as:</p>
  
  <pre><code>$query = "SELECT * FROM table WHERE lon BETWEEN '$minLon' AND '$maxLon' AND lat BETWEEN '$minLat' AND '$maxLat'";
  </code></pre>
  
  <p>This works fine, and I use a function to calulate and display the actual distance between users at output stage, but I'd like to be able to sort the results by decreasing or increasing distance at the query stage. </p>
  
  <p>Is there any way of doing this?</p>