Home » Php » php – How to populate <select> with ENUM values?

php – How to populate <select> with ENUM values?

Posted by: admin July 12, 2020 Leave a comment

Questions:

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?

How to&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>

Answer:

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;
}