What's wrong with my MySQL query? (using BETWEEN)
I'm trying to select businesses from my database who fall within a 10mi radius of the user. Testing shows that the problem lies in my query (though no MySQL error is thrown). The variables $lat and $lng are imported from Javascript and they, too, are fine. I suspect 开发者_Go百科the issue is something to do with my use of BETWEEN, as this is the first time I've used it. Any ideas?
$r = 20; // in miles
$lat_min = $lat - ($r / 69);
$lat_max = $lat + ($r / 69);
$lng_min = $lng - $r / abs(cos(deg2rad($lat)) * 69);
$lng_max = $lng + $r / abs(cos(deg2rad($lat)) * 69);
$query = "SELECT name FROM businesses WHERE $lat BETWEEN $lat_min AND $lat_max $lng BETWEEN $lng_min AND $lng_max ORDER BY Rand() LIMIT 6";
The query should be:
SELECT name FROM businesses
WHERE THE_ACTUAL_NAME_OF_THE_COLUMN BETWEEN $lat_min AND $lat_max
AND THE_NAME_OF_THE_NEXT_COLUMN BETWEEN $lng_min AND $lng_max
ORDER BY Rand() LIMIT 6
Somehow $lat does not look like a column name in the table. Also you were missing an AND.
Looks like you have you're missing and AND
e.g.
SELECT
name
FROM
businesses
WHERE
$lat BETWEEN $lat_min AND $lat_max
AND $lng BETWEEN $lng_min AND $lng_max
ORDER BY Rand() LIMIT 6
Like, the other answers, and to be sure, place ( ).
$query = 'SELECT name
FROM businesses
WHERE
('.$lat.' BETWEEN "'.$lat_min.'" AND "'.$lat_max.'")
AND ('.$lng.' BETWEEN "'.$lng_min.'" AND "'.$lng_max.'")
ORDER BY Rand() LIMIT 6";
$query = "SELECT name FROM businesses WHERE $lat BETWEEN $lat_min AND $lat_max AND $lng BETWEEN $lng_min AND $lng_max ORDER BY Rand() LIMIT 6";
Assuming $lat and $lng resolve to actual column names, I think you're just missing an "AND". Sometimes, just formatting the SQL statement can reveal the issue.
SELECT name
FROM businesses
WHERE $lat BETWEEN $lat_min AND $lat_max
**AND** $lng BETWEEN $lng_min AND $lng_max
ORDER BY Rand() LIMIT 6;
I think you need an AND in the WHERE clause...
WHERE ($lat BETWEEN $lat_min AND $lat_max) AND ($lng BETWEEN $lng_min AND $lng_max)
精彩评论