Answer a question

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?

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>
Logo

华为、百度、京东云现已入驻,来创建你的专属开发者社区吧!

更多推荐