如何使用mysqli和PHP参考纬度和经度检查数据库中是否存在数据?

时间:2018-04-10 14:18:11

标签: php mysqli

如何使用mysqli和PHP参考纬度和经度检查数据库中是否存在数据?

测试表

______________________________________________________________
|__id__|__langtitude_coolumn_name__|__lattitude_coolumn_name_|
|___1__|_______37.802924___________|______-98.448061_________|
|___2__|_______37.798518___________|______-98.459890_________|
|___3__|_______37.797262___________|______-98.454006_________|

我使用此代码检查数据是否存在于数据库中使用mysqli和PHP参考纬度和经度距离我的位置纬度不到100公里纬度= 37.799773和经度= -98.460878

但我没有任何结果,我该怎么办?

<?PHP
$lattitude_value= "37.799773";
$langtitude_value = "-98.460878";
$stmt = $db_mysqli->prepare("SELECT U.* FROM table_name WHERE st_distance_sphere( POINT(U.langtitude_coolumn_name, U.lattitude_coolumn_name), POINT(?, ?)) <= 100000");
$stmt->bind_param("ss", $langtitude_value, $lattitude_value);
$stmt->execute();
$arr = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
if(!$arr)
{
    echo "not have data";
}
else
{
    echo "get data";
}
?>

1 个答案:

答案 0 :(得分:0)

试试这个,它将为您提供GPS坐标对的Id,纬度,经度以及100公里范围内所有匹配坐标的公里距离。

组合HTML / PHP / MySQL:

   $host = 'localhost';
   $dbname = 'dbname';
   $user = 'dbusername';
   $pass = 'password';

   $conn = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
   $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
   $conn->exec("SET CHARACTER SET utf8");

   $sql = "SELECT
                id,latitude,longitude, (
                  6371 * acos (
                  cos ( radians(37.799773) )
                  * cos( radians( latitude ) )
                  * cos( radians( longitude ) - radians(-98.460878) )
                  + sin ( radians(37.799773) )
                  * sin( radians( latitude ) )
                )
            ) AS distance
            FROM table_name
            HAVING distance < 100
            ORDER BY distance";

   $sqlprep = $conn->prepare($sql);

   if($sqlprep->execute()) {
       while($row = $sqlprep->fetch(PDO::FETCH_OBJ)){
             echo "Id: ".$row->id." Latitude: ".$row->latitude." Longitude: ".$row->longitude." Distance: ".$row->distance."<br>\n";
       }
   }