kotekzot
kotekzot

Reputation: 1588

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?

Upvotes: 7

Views: 8050

Answers (2)

Anna
Anna

Reputation: 554

Here's another solution you can use as a helper function whenever you want to get the enum values into an array to use as needed.

public static function getSQLEnumArray($table, $field, $db){
    $row = $db->query("SHOW COLUMNS FROM ".$table." LIKE ".$field)->fetch(PDO::FETCH_ASSOC);
    preg_match_all("/'(.*?)'/", $row['Type'], $categories);
    $fields = $categories[1];
    return $fields;
}

Upvotes: 4

kotekzot
kotekzot

Reputation: 1588

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>

Upvotes: 8

Related Questions