Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I store US States in my database or a PHP array?

How should I store States and Countries?

Option 1) I could create a database table called states, and have 'id', 'state', and 'state_abbr'. I could then reference that by 'id' in the users table.

Option 2) I could create a PHP array and use that to populate the states drop down menu, and avoid querying the database altogether. The key for the array would be the value inserted in the database for that user.

States don't change, and so the data should be static. What's the best way to store this information and why? Wouldn't a PHP array be faster? Why does it seem like the database is the best way to store it then?

Thoughts?

like image 500
Jacob Haug Avatar asked Sep 14 '12 23:09

Jacob Haug


2 Answers

A wise database designer once told me, "Everything you know about state codes is wrong."

  • These are two-letter codes, not abbreviations. (The abbreviation for California is "Calif.", and the abbreviation for Ohio is "Ohio".)
  • There are more than 50 of them.
  • Not all of the two-letter codes refer to states. They also refer to "possessions" like "Federated States of Micronesia" and "Palau".
  • They're not unique. One two-letter code, AE, refers to four different military "states" (Armed Forces Europe, Armed Forces Canada, Armed Forces Middle East, and Armed Forces Africa).
  • Military "state" codes may change as troop strength changes. Send a few hundred thousand troops into Africa, and you're likely to see the code for Armed Forces Africa change from "AE" to "AF".
  • There are a dozen or so territories that aren't yet in this list. Some of these are of strategic interest (Wake Island, Midway Islands, etc.), and their status could easily change.

Given that you're not likely to know all these things about such a common thing as USPS state codes, it just makes more sense to store them in a table. Tables are easier to maintain at run time than a PHP array is.

like image 157
Mike Sherrill 'Cat Recall' Avatar answered Nov 07 '22 21:11

Mike Sherrill 'Cat Recall'


Because the database is the best way to store it.

What if next year your company decides to go international? So now you need countries, and a dependent dropdown for states.

So you need to add europe, then africa.. Thats a TON of countries, along with a ton of states. You will need one big array.

Then your boss wants a report by country.

Much easier to manage if you have it all in a database.

like image 30
Kris Avatar answered Nov 07 '22 21:11

Kris