Search within x mile radius with PHP and MYSQL


This is just a dump of our usage, you may need to heavily modify the code:

if(!empty($_GET['zipcode'])){
$cur_state = ''; $cur_city = '';
$zipcode = queryDB("SELECT latitude, longitude FROM zipcodes WHERE zipcode='".escape($_GET['zipcode'])."' LIMIT 1",'a');
if(!empty($zipcode)){
$distance = 30;
$sql = "SELECT zipcode, ( 3959 * acos( cos( radians(".$zipcode['latitude'].") ) * cos( radians( latitude ) ) * cos( radians( longitude ) - radians(".$zipcode['longitude'].") ) + sin( radians(".$zipcode['latitude'].") ) * sin( radians( latitude ) ) ) ) AS distance FROM zipcodes HAVING distance < $distance ORDER BY distance";
$zipcodes = queryDB($sql, 'r');
$where = '';
while($zipcode = mysqli_fetch_array($zipcodes)){
	$where .= "zipcode='".$zipcode['zipcode']."' || ";
}
$where = rtrim($where, '|| ');
$dealers = queryDB("SELECT * FROM dealers WHERE $where ORDER BY state, city, name ASC", 'r');
if(mysqli_num_rows($dealers) > 0){
echo "<br><h3>Dealers found within a 30 mile radius:</h3>";
while($dealer_info = mysqli_fetch_assoc($dealers)){
if($dealer_info['state'] != $cur_state){ echo "<br><h1>".$dealer_info['state']."</h1><hr><br>"; $cur_state = $dealer_info['state'];  }
if($dealer_info['city'] != $cur_city){ $end = true; echo "<h4 style='margin-bottom: 10px; margin-top: 10px;'>".$dealer_info['city']."</h4></ul>"; $cur_city = $dealer_info['city'];  }
echo "<li style='padding-bottom: 10px;'><a href='http://".$dealer_info['website']."' target='_blank'>".$dealer_info['name']."</a><br>".$dealer_info['phone']. "<br>".$dealer_info['street'].'<br>'.$dealer_info['city'].', '.$dealer_info['state'].' '.$dealer_info['zipcode']."</li>";
if($end){ echo "</ul>"; $end = false;}
}
}




Shane Stebner

Author: Shane Stebner

Shane is a successful web-developer specializing in responsive design, and the open-source LAMP stack. Over the years, he's gained in-depth experience with Stripe, Twilio, PhantomJs, Authorize.net, PayPal, Facebook, Twitter, and many other plugins/APIs.


comments powered by Disqus