(actually written sunday but i had other more important things on my blog so i figured i’d stuff this one lower in the list for the search engines)

Here’s the issue:  You have a lot of database fields that record one of the 50 United States of America.  You want to repeatedly show a dropdown list of all the states and pre-select the one that is currently stored in the database.  If no value is selected you want the dropdown list to just say “select a state”.

I wrote a nice little PHP function to take care of this need for me in my latest app and thought it might be useful to the community at large so here it is:

database stuff:
your database has a table named “states” and one field named “name”.  You can add a field for postal state code or whatever you like to make it suit your needs, but my version was simple and i gave it just one field, which is the names of the states.

your application:
your application sets a variable to the name of a state.  you can make the variable whatever you like; just make it match when you call the function.

 

html stuff:
your html code needs to have the following code:

 

The Function
here’s the function.  stick this up somewhere early in your application before you call it from the HTML.

 

 

Hope this is helpful to someone.  It’s saving me at least 50 lines of code every time i use it 😀

Leave a Reply