Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to populate <select> with ENUM values?

I want to populate an HTML <select> with options from an ENUM field in a MySQL database using PHP and PHP Data Objects (PDO). How can I do this?

like image 921
kotekzot Avatar asked May 30 '12 22:05

kotekzot


1 Answers

Vanilla PHP implementation:

<select>
<?
    $result = mysql_query('SHOW COLUMNS FROM '.$table_name.' WHERE field="'.$column_name.'"');
    while ($row = mysql_fetch_row($result)) {
            foreach(explode("','",substr($row[1],6,-2)) as $option) {
                print("<option>$option</option>");
            }
        }
?>
<select>

PHP Data Objects implementation

<select>
<?
    $sql = 'SHOW COLUMNS FROM '.$table_name.' WHERE field="'.$column_name.'"';
    $row = $db->query($sql)->fetch(PDO::FETCH_ASSOC);
    foreach(explode("','",substr($row['Type'],6,-2)) as $option) {
            print("<option>$option</option>");
        }
?>
</select>
like image 199
kotekzot Avatar answered Sep 29 '22 16:09

kotekzot