What are some best practices for querying a database using SQL code in PHP to retrieve data within a specific radius of a given location?

When querying a database using SQL code in PHP to retrieve data within a specific radius of a given location, you can use the Haversine formula to calculate distances between two points on the Earth's surface. This formula takes into account the curvature of the Earth and provides accurate results for geographical calculations. By incorporating this formula into your SQL query, you can efficiently retrieve data within a specified radius of a given location.

<?php
$lat = 40.7128; // Latitude of the center point
$lng = -74.0060; // Longitude of the center point
$radius = 10; // Radius in kilometers

$sql = "SELECT id, name, lat, lng, 
    ( 6371 * acos( cos( radians($lat) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians($lng) ) + sin( radians($lat) ) * sin( radians( lat ) ) ) ) 
    AS distance 
    FROM locations 
    HAVING distance <= $radius 
    ORDER BY distance";

// Execute the SQL query and fetch the results
?>