简体   繁体   中英

Possible MySql syntax issue

I'm trying to figure out why my query isn't working, but it doesn't make sense to me. I'm accessing a database via php that lists states and their affiliated cities/towns, and I have a javascript script which displays them as menus. Each state has an ID which is incremented by 100,000 (meaning in the database, "Alabama" is 100,000 and "Alaska" is 200,000.) So I tested my query out in MySQL and it works properly, and I tested the javascript value that was being sent to the php script and it was the correct one, but the returned menu is containing many more values than it should.

My query looks like:

mysql_query("SELECT * FROM fullstates WHERE code > '$state' AND code < '$state' + 100000");

where state is the ID of the previous state that was picked. The only thing I could think of is that the AND isn't working properly?

Are your codes numeric or text? Seems like they should be numeric, in which case you should drop your single quotes:

mysql_query("SELECT * FROM fullstates WHERE code > $state AND code < ($state + 100000)");

You should also parameterize this, but that's another concern.

mysql_query("SELECT * FROM fullstates WHERE code > '$state' AND code < '$state' + 100000");

...WHERE 200,000 > 100,000 AND 200,000 < 100,000 + 100,000

if the value of state = 100,000 and code is 200,000, then the first boolean evaluation is true, but now you check if code(200,000) is LESS than state(100,000) + 100,000.

In other words you're checking if 200,000 < 200,000, so your check is WHERE (TRUE[first expression] AND FALSE[second expression])

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