Last active
December 21, 2015 14:18
-
-
Save Abhinav1217/a8732441729ee21ac733 to your computer and use it in GitHub Desktop.
Get enum values from some column in Mysql/Mariadb with PHP or PDO
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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