简体   繁体   中英

MySQL Select Query Multiple Between Arguments, Variable not Working PHP

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM