I'm setting up a lat/long search for nearby cities. It is based on Google's example.
Code
$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);
Error
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 开发者_Python百科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
Update -- Working Example
$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);
Long
is a reserved word.
Escape your column names so MySQL doesn't think you're trying to cast a comma:
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
Long is a mysql keyword. You should either rename the column or enclose the column name in back ticks.
精彩评论