如何在PHP中获取枚举的默认值?

时间:2011-01-07 09:27:11

标签: php mysql

如何在PHP / MySQL中获取枚举的默认值?我希望将它用作单选按钮/下拉列表。

4 个答案:

答案 0 :(得分:3)

mysql> create table choices ( choice enum('a','b') not null default 'b');
Query OK, 0 rows affected (0.00 sec)

mysql> desc choices;
+--------+---------------+------+-----+---------+-------+
| Field  | Type          | Null | Key | Default | Extra |
+--------+---------------+------+-----+---------+-------+
| choice | enum('a','b') | NO   |     | b       |       |
+--------+---------------+------+-----+---------+-------+

mysql> show columns from choices like 'choice';
+--------+---------------+------+-----+---------+-------+
| Field  | Type          | Null | Key | Default | Extra |
+--------+---------------+------+-----+---------+-------+
| choice | enum('a','b') | NO   |     | b       |       |
+--------+---------------+------+-----+---------+-------+

要么能够在Default字段

上生成查询

答案 1 :(得分:2)

此查询:

SELECT 
  COLUMN_TYPE 
FROM 
  information_schema.COLUMNS 
WHERE 
  TABLE_SCHEMA = 'yourDatabase' 
  AND TABLE_NAME = 'yourTable' 
  AND COLUMN_NAME = 'yourEnumColumn'

将返回类似enum('v1','v2','v3')的列类型字符串。然后,您可以使用简单的字符串操作(可能会爆炸)将其转换为适合您的任何格式。

答案 2 :(得分:1)

这是CakePHP bakery的一个片段,您可以将其用于您的目的。它会给你一般的想法:

//Get the values for the specified column (database and version specific, needs testing)
$result = $this->query("SHOW COLUMNS FROM {$tableName} LIKE '{$columnName}'");

//figure out where in the result our Types are (this varies between mysql versions)
$types = null;
if     ( isset( $result[0]['COLUMNS']['Type'] ) ) { $types = $result[0]['COLUMNS']['Type']; $default = $result[0]['COLUMNS']['Default']; } //MySQL 5
elseif ( isset( $result[0][0]['Type'] ) ) { $types = $result[0][0]['Type']; $default = $result[0][0]['Default']; } //MySQL 4
else { return array(); } //types return not accounted for

//Get the values
$values = explode("','", preg_replace("/(enum)\('(.+?)'\)/","\\2", $types) );

希望有所帮助!

答案 3 :(得分:1)

这将对您有所帮助:

class enum_values {

public $values;

public function __construct($table, $column){

    $sql = "SHOW COLUMNS FROM $table LIKE '$column'";
    if ($result = mysql_query($sql)) { // If the query's successful

        $enum = mysql_fetch_object($result);
        preg_match_all("/'([\w ]*)'/", $enum->Type, $values);
        $this->values = $values[1];

    } else {

        die("Unable to fetch enum values: ".mysql_error());

    }

  }
}

我在这里找到了这个:http://barrenfrozenwasteland.com/index.php?q=node/7

但有一点,我想提一下成功获取列还取决于数据库用户拥有的权限。