I want to populate my dropdowns with enum possible values from a DB automatically. Is this possible in MySQL?
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.
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)
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.
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; }
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With