I have a database of users. Each user has to enter during registration a street address, state, city, zipcode.
I also have in my database tables for States, Cities, Counties, Zipcodes. These tables are filled with all the US states, counties, cities and zipcodes available.
-Zipcodes are linked to cities only.
-Cities are linked to counties and states. Each city has unique city_id
-Counties are linked to states only. Each county has unique county_id
-Each state has unique state_id
My PHP page specifically for addresses consists of:
-SELECT for States (state_name as text; state_id as value)
-TEXTBOX for City (with only city_name as value)
-TEXTBOX for Zipcode
I use PHP Session to store values entered by user, in case of failed form validation.
When the user submits I want to be able to put in the database the city_id (since that id will also contain county_id and state_id). But what the user submits is a city_name. How can I match that?
Do i need a search in the database on the form validation and see if I can find the city based on what the user entered? I suppose I would need a perfect match.
Use autocomplete and retrieve with jquery and ajax cities (including the city_id) based on what the user types and then store somewhere the city_id value?
How should I do it?
Your query to get city_id
based on either city_name
or zipcode
might look like this
SELECT c.city_id
FROM cities c JOIN zipcodes z
ON c.city_id = z.city_id
WHERE c.city_name = 'Baltimore'
OR z.zipcode = '21201'
GROUP BY c.city_id
UPDATE To get city_id
by one of its zipcodes
SELECT city_id
FROM zipcodes
WHERE zipcode = '21201'
GROUP BY city_id
Here is SQLFiddle demo
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.