SQL search configuration
I am not very good at SQL and I have a simple zipcode finder that I created for my website. The SQL is as follows:
$query = "select * from zipcodes2 where ZipCode like \"%$trimmed%\"
*\"%$trimmed%* of course is the actual zipcode the user enters in. It wor开发者_如何转开发ks great but now I want to make it more advance by letting the user search for city or state and not just zipcode. I already have the columns created and they are named "City" and "State". What exactly should I put in the SQL line? Will I have to change any other part of the code, specifically the \"%$trimmed%\ part?
This is not a great approach but you can get close to what you want with this:
$query = "select * from zipcodes2 where ZipCode like '%$trimmed%' or (CONCAT(City, ',', State) = '$trimmed')"
But you must make sure the the user's response has no white space so it comes out as Chicago,IL
and not anything like Chicago, IL
or Chicago , IL
.
You can do this by putting this before your query:
$trimmed = preg_replace( '/\s+/', ' ', $trimmed );
You could try something like this:
select *
from zipcodes2
where
(
ZipCode like '%$trimmed%'
OR City like '%City%'
OR State like '%State%'
)
You should be able to accomplish by modifying the SQL query to something like:
SELECT * FROM zipcodes2 WHERE ZipCode LIKE \"%$trimmed%\" OR (State = \"$state_vairable\" AND City = \"$city_variable\")
This of course depends on your end goal. The above works if you're trying to match on explicit city/state combinations.
If you want people to be able to find the zipcodes of all the places called "townsville" in the us, remove the parenthesis and change the AND to an OR.
精彩评论