I'm developing an app that, for a given location (coordinate lat/long pair), it displays all entities (pulled from database) located within a given radius from the given starting location.

I've tested, and the logic that I'm using to find the nearest locations works great. However, in my PHP script to communicate with the MySQL table, I'm running into an issue.

Here is my query that I am attempting, which gives me no results from the table:

$sql = "SELECT * FROM merchants WHERE latitude BETWEEN '$lat1' AND '$lat2' AND longitude BETWEEN '$lon1' AND -90.2745 AND category='$merchCategory'";           

However, from echoing out $lat1, $lat2, $lon1, and $lon2, I know that they contain valid values (that should produce results from the query (FYI: these 4 variables represent a radius square from a given location; latitude and longitude are columns in the table.)

$lon1= -90.644843447 $lon2= -90.274500553 $lat1= 38.3496784638 $lat2= 38.6395335362

However, this works (just hard-coding in the value, not referencing it w/ the $lon2 variable:

$sql = "SELECT * FROM cashbackengine_merchants WHERE latitude BETWEEN '$lat1' AND '$lat2' AND longitude BETWEEN '$lon1' AND **-90.2745** AND category='$merchCategory'";            

As does this:

$sql = "SELECT * FROM cashbackengine_merchants WHERE latitude BETWEEN '$lat1' AND '$lat2' AND longitude BETWEEN **-90.64484** AND '$lon2' AND category='$merchCategory'";           

Yet no problems with the latitude at all. I feel strongly this has something to do with syntax and likely is something very simple. Any help is greatly appreciated!

share|improve this question

1 Answer

up vote 0 down vote accepted

Try this

$sql = "SELECT * FROM merchants WHERE latitude BETWEEN '$lat1' AND '$lat2' AND longitude BETWEEN $lon1 AND $lon2 AND category='$merchCategory'";

I'm not sure but I think this is because BETWEEN requires two numbers for your case and you're passing it as a string '$lon'. And when you hardcode one value, other one is automatically converted to a number value.

Sidenote: Look into prepared statements (best) or escaping the string, as this opens you to sql injections if lat/lon values are being entered by the user.

share|improve this answer
Spot on about what was happening. Thanks! – lreichold Aug 4 '12 at 13:14

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.