1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...

Build dropdown from Mysql SET or ENUM fields


We need to populate dropdown fields from Mysql SET or ENUM fields pretty often. So here is how I use to do it.
Lets say ‘test’ is a table that has a field, ‘agree’ of type ‘SET’ having values ‘Yes’ and ‘No’. On the front end of my application I want to show a dropdown/select field having options ‘Yes’ and ‘No’.

First get the field’s ‘SET’ values. This is a function I wrote for myself to get the ENUM field values.

function getEnumFieldValues($tableName, $fieldName){
$field_query = mysql_query("show columns from $tableName where Field='$fieldName'");
if(mysql_num_rows($field_query) <= 0) return false;
$fieldDetail = mysql_fetch_array($field_query);
$type = preg_replace('/(^set\()|(^enum\()/i', '', $fieldDetail['Type']);
$enumFields = substr($type, 0, -1);
$fieldSplit = split(',', $enumFields);
return $fieldSplit;
}

Using the values, populate the dropdown field like this.

$enumFields = getEnumFieldValues('agree', 'test');
echo '<select name="agree">';
foreach($enumFields as $value){
echo '<option value="' . $value . '">' . $value . '</option>';
}
echo '</select>';

That's all. Now put any table and field names to get the ENUM/SET field values and create your dropdown.

Bookmark and Share

,

  1. #1 by Benjamin on January 14th, 2010

    Super, works a treat, thanks!

  2. #2 by Imran on January 14th, 2010

    Good to know that :-)

  3. #3 by Junnjun M. on January 29th, 2010

    Hi there…How can I remove the qoutes (”) that wrap values??Thanks

  4. #4 by Imran on January 29th, 2010

    Handling quotes is always a bit tricky. You need to convert quotes to html entities, which means use the code like following:

    $enumFields = getEnumFieldValues('agree', 'test');
    echo '<select name="agree">';
    foreach($enumFields as $value){
    echo '<option value="' . htmlentities($value) . '">' . $value . '</option>';
    }
    echo '</select>';
    

    When you are using the submitted value in your php script, get the value like this:

    $value = html_entity_decode($value);

    Hope this helps.

  5. #5 by wzyhcmseea on March 7th, 2010

    sf0ptF hexfvjohjyao, [url=http://uvjhfvcjiuti.com/]uvjhfvcjiuti[/url], [link=http://vlyltgsymdjl.com/]vlyltgsymdjl[/link], http://ffntliyuocpb.com/

  6. #6 by tezza on March 11th, 2010

    You have tested it and writing form your personal experience or you find some information online?

(will not be published)
Security Code:

  1. No trackbacks yet.