php mysql查询纬度经度语法

时间:2011-04-08 04:32:49

标签: php mysql sql latitude-longitude

我正在为附近的城市设置一个纬度/经度搜索。它基于Google的example

代码

    $query = sprintf("SELECT Zip, City, State, Lat, Long, ( 3959 * acos( cos( radians('%s') ) * cos( radians( lat ) ) * cos( radians( lng ) - radians('%s') ) + sin( radians('%s') ) * sin( radians( lat ) ) ) ) AS distance FROM Zips HAVING distance < '%s' ORDER BY distance LIMIT 0 , 18",
      mysql_real_escape_string($lat),
      mysql_real_escape_string($lng),
      mysql_real_escape_string($lat),
      mysql_real_escape_string($radius));
    $result = mysql_query($query, $dbConn);

错误

Invalid query: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Long, ( 3959 * acos( cos( radians('37') ) * cos( radians( lat ) ) * cos( radians' at line 1 Whole query: SELECT Zip, City, State, Lat, Long, ( 3959 * acos( cos( radians('37') ) * cos( radians( lat ) ) * cos( radians( lng ) - radians('-122') ) + sin( radians('37') ) * sin( radians( lat ) ) ) ) AS distance FROM Zips HAVING distance < '50' ORDER BY distance LIMIT 0 , 18

更新 - 工作示例

    $query = sprintf("SELECT `Zip`, `City`, `State`, `Lat`, `Long`, ( 3959 * acos( cos( radians('%s') ) * cos( radians( `Lat` ) ) * cos( radians( `Long` ) - radians('%s') ) + sin( radians('%s') ) * sin( radians( `Lat` ) ) ) ) AS distance FROM Zips HAVING distance < '%s' ORDER BY distance LIMIT 0 , 18",
      mysql_real_escape_string($lat),
      mysql_real_escape_string($lng),
      mysql_real_escape_string($lat),
      mysql_real_escape_string($radius));
    $result = mysql_query($query, $dbConn);

2 个答案:

答案 0 :(得分:6)

Longreserved word

转义您的列名,以便MySQL不认为您正在尝试使用逗号:

SELECT `Zip`, `City`, `State`, `Lat`, `Long`, 
( 3959 * acos( cos( radians('%s') ) * cos( radians( `Lat` ) ) * cos( radians( `Long` ) - radians('%s') ) + sin( radians('%s') ) * sin( radians( `Lat` ) ) ) ) AS distance 
FROM Zips 
HAVING distance < '%s' 
ORDER BY distance LIMIT 0 , 18

答案 1 :(得分:4)

是一个mysql关键字。您应该重命名列或将列名称包含在后面的刻度中。