php - 纬度经度脚本给出 MySQL 错误 "You have an error in your SQL syntax; ... for the right syntax to use near ' long”

标签 php android mysql

我正在做一个Android应用程序。它也有一个服务器后端。我需要从数据库中选择边界正方形或圆形的纬度和经度。我正在使用下面的代码..但它不起作用。请帮助我..

<?php

$lat = $_GET['lat'];
$lon = $_GET['lon'];
$rad = 10;

$R = 6371;

$maxLat = $lat + rad2deg($rad/$R);
$minLat = $lat - rad2deg($rad/$R);
$maxLon = $lon + rad2deg($rad/$R/cos(deg2rad($lat)));
$minLon = $lon - rad2deg($rad/$R/cos(deg2rad($lat)));


$lat = deg2rad($lat);
$lon = deg2rad($lon);

$con=mysql_connect("localhost","root","");
mysql_select_db("circle",$con);


$sql="Select name,acos(sin($lat)*sin(radians(`lat`))+cos($lat)*cos(radians(`lat`))*cos(radians(`long`)-$lon))*$R As D From circle Where acos(sin($lat)*sin(radians(`lat`))+cos($lat)*cos(radians(`lat`))*cos(radians(`long`)-$lon))*$R < $rad";

$rslt= mysql_query($sql);
$row=mysql_num_rows($rslt);
$arr=mysql_fetch_assoc($rslt);
print_r($arr);

?>

谢谢

最佳答案

由于long是保留字,因此不能直接将其用作列名。 (您确定您的列不是 name lon 吗?)

如果列名为long,您可以使用反引号将其转义:

$sql = "select name from circle where lat > $minLat and lat < $maxLat and `long` > $minLon and `long` < $maxLon";

这样 MySQL 就知道您正在使用列名,并且不会尝试将文本解释为其他内容。

更新

来自 OP 的新查询,按距离排序。 (我确实将 D 重命名为 distance。)

$sql="SELECT name, acos(sin($lat)*sin(radians(`lat`))+cos($lat)*cos(radians(`lat`))*cos(radians(`long`)-$lon))*$R AS `distance`
    FROM circle
    WHERE `distance` < $rad
    ORDER BY `distance` ASC";

请注意,此查询会很慢,因为它无法使用索引来限制行数或排序。它必须先计算每行的距离,然后才能确定该行是否应包含在结果集中。如果您的表包含 5 行,这并不重要,但如果有 500,000 行,那就很重要了。

关于php - 纬度经度脚本给出 MySQL 错误 "You have an error in your SQL syntax; ... for the right syntax to use near ' long”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9452563/

相关文章:

php - 在 FOP 生成的 PDF 文件中包含 PDF 文件

java - 与 Android 中的 AsyncTask 相关

java - 如何以 JSON 格式将 Android 中的数据发布到服务器?

当字段有空格时 MySQL 准备好的语句不起作用

php - 从 PDO 获取查询更新多行

mysql - 在创建索引时查询期间与 mysql 服务器失去连接,但之后仍然获取索引

PHP,mysql_query 只是不工作

php - 如何使用php从mysql数据库中检索所有数据?

android - 像 <b> <i> <a> 这样的 html 标签在发送到 ACTION_SEND 时不能与 HTML.fromHtml() 一起使用

php - PHP/MySQL 中的异步消息传递?