我想使用PHP和PHP数据对象(PDO)在MySQL数据库中使用ENUM字段中的选项填充HTML <select>
。我怎么能这样做?
答案 0 :(得分:7)
Vanilla PHP实施:
<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数据对象实现
<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>
答案 1 :(得分:4)
这是另一种解决方案,只要您想将枚举值放入数组中以便根据需要使用,就可以将其用作辅助函数。
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;
}