Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Get enum values from some column in Mysql/Mariadb with PHP or PDO
<?php
/** This snippet can be used as <options> in <SELECT> in html **/
?>
<select>
<?php
$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
/** Same Functionality using PDO **/
?>
<select>
<?php
$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>
<?php
/** A resuable Function which returns an array of the enum options **/
function getEnumValues($table_name, $column_name)
{
$sql = 'SHOW COLUMNS FROM {$table_name} WHERE field="{$column_name}"';
$row = $pdo->query($sql)->fetch(PDO::FETCH_ASSOC);
return explode("','",substr($row['Type'],6,-2));
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment