I got this far by reading here on Stack Overflow. I have a table full of delivery hubs. Table structure is:
name - name of hub
zip - zip code of hub
lng - longitude of hub
lat - latitude of hub
radius - delivery radius
I am currently using this to get the closest delivery hub:
$dist1 = '20';
$pdo = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $pdo->prepare("SELECT name,
lat,
lng,
zip,
radius,
3956 * 2 * Asin(Sqrt(Power(Sin(( :lat - lat ) * Pi() / 180 / 2), 2) +
Cos(:lat * Pi() / 180) * Cos(
lat * Pi() / 180) *
Power(Sin(( :lng - lng ) * Pi()
/
180 / 2), 2))) AS dist
FROM hubs
WHERE lng BETWEEN ( :lng - :dist1 / Cos(Radians(:lat)) * 69 ) AND ( :lng +
:dist1 / Cos(Radians(:lat
)) * 69 )
AND lat BETWEEN ( :lat - ( :dist1 / 69 ) ) AND ( :lat + ( :dist1 / 69 ) )
HAVING dist < :dist1
ORDER BY dist
LIMIT 100 ");
$stmt->execute([
'lng' => $lng,
'lat' => $lat,
'dist1' => $dist1
]);
while ($row = $stmt->fetch()) {
if ($row['radius'] >= $row['dist']){
echo $row['name'];
echo " - ";
echo $row['zip'];
echo " - ";
echo $row['dist'];
echo "<br>";
}
}
I would optimally like to eliminate the $dist1 variable from the query and instead only display the closest delivery hubs that deliver in that radius set by the hub, using only MySQL, not PHP (as I am using now).
How can I do this?