How to fill <select> using ENUM values?

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

+6
source share
2 answers

PHP Vanilla 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 Object 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> 
+7
source

Here's another solution that you can use as a helper function whenever you want to get the enumeration values ​​into an array, which will be used 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; } 
+4
source

Source: https://habr.com/ru/post/917055/


All Articles