Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get enum possible values in a MySQL database?

Tags:

php

mysql

I want to populate my dropdowns with enum possible values from a DB automatically. Is this possible in MySQL?

like image 390
Shamoon Avatar asked Feb 28 '10 04:02

Shamoon


People also ask

How do I query enum in SQL?

This means that you can use the following SELECT statement to find rows into which invalid ENUM values were assigned: mysql> SELECT * FROM tbl_name WHERE enum_col=0; The index of the NULL value is NULL . The term “index” here refers to a position within the list of enumeration values.

How enum values are stored in MySQL?

The ENUM data type is stored in two locations: the set of values is stored in the table metadata; in each row, only the set index is stored, as integer, which requires one byte for enums up to 255 entries large, then two for up to 65535 entries (see MySQL reference)

Does MySQL support enum?

In MySQL, an ENUM is a string object whose value is chosen from a list of permitted values defined at the time of column creation. The ENUM data type provides the following advantages: Compact data storage. MySQL ENUM uses numeric indexes (1, 2, 3, …) to represents string values.


2 Answers

I have a codeigniter version for you. It also strips the quotes from the values.

function get_enum_values( $table, $field ) {     $type = $this->db->query( "SHOW COLUMNS FROM {$table} WHERE Field = '{$field}'" )->row( 0 )->Type;     preg_match("/^enum\(\'(.*)\'\)$/", $type, $matches);     $enum = explode("','", $matches[1]);     return $enum; } 
like image 107
Patrick Savalle Avatar answered Oct 07 '22 19:10

Patrick Savalle


You can get the values by querying it like this:

SELECT SUBSTRING(COLUMN_TYPE,5) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA='databasename'      AND TABLE_NAME='tablename'     AND COLUMN_NAME='columnname' 

From there you'll need to convert it into an array:

  • eval that directly into an array if you're lazy (although MySQL's single quote escape might be incompatible), or
  • $options_array = str_getcsv($options, ',', "'") possibly would work (if you alter the substring to skip the opening and closing parentheses), or
  • a regular expression
like image 26
Matthew Avatar answered Oct 07 '22 17:10

Matthew