PHP Tutorial: Put MySQL ENUM values into drop down select box

March 16, 2011 at 3:12 am 4 comments

If you have an ENUM field in your table schema then you don’t want to go through the hassle of re-writing out all of the different ENUM values when you do an online form or CMS update system. This piece of code will take all of your ENUM values and put them into a select box so the choices displayed in the drop down are always up to date.

$table_name = "your_table_name"
$column_name = "field_with_enum_options";

echo "<select name=\"$column_name\">";
$result = mysql_query("SELECT COLUMN_TYPE FROM INFORMATION_SCHEMA.COLUMNS
    WHERE TABLE_NAME = '$table_name' AND COLUMN_NAME = '$column_name'")
or die (mysql_error());

$row = mysql_fetch_array($result);
$enumList = explode(",", str_replace("'", "", substr($row['COLUMN_TYPE'], 5, (strlen($row['COLUMN_TYPE'])-6))));

foreach($enumList as $value)
    echo "<option value=\"$value\">$value</option>";

echo "</select>";
enumList
About these ads

Entry filed under: Code Snippets, for PHP, for Web Design, Free Code, Freeware, MySQL, PHP, Programming Languages. Tags: , , , , , , , , .

DOJO Tutorial: Clear All Data From The Grid Pits Of Doom Update!

4 Comments Add your own

  • 1. Philippe Vincke  |  May 13, 2011 at 8:36 am

    Thanks for this tutorial although there’s a minor problem in your sql : the variables with tablename and columnname are inversed.

    Never the less, this saved me some time of trial and error.

    Thx.

  • 2. Jade  |  May 13, 2011 at 1:48 pm

    Thanks I’ll fix that.

  • 3. eegsdg  |  September 3, 2012 at 2:15 pm

    Bad written in – echo “”; – it must be ‘$column_name’

  • 4. Amanda  |  October 26, 2012 at 5:12 pm

    thank you so much for this! saved me a lot of headaches.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Trackback this post  |  Subscribe to the comments via RSS Feed


Lost In Oblivion

March 2011
M T W T F S S
« Feb   Apr »
 123456
78910111213
14151617181920
21222324252627
28293031  

Recent Posts

Feeds


Follow

Get every new post delivered to your Inbox.