Home >Backend Development >PHP Tutorial >How to Populate Dropdowns Dynamically with Enum Values from a MySQL Database?
Populating Dropdowns with Enum Values from a MySQL Database
Question:
How can I automatically populate my dropdowns with the possible enum values stored in a MySQL database?
Answer:
Yes, it is possible to dynamically populate dropdowns with enum values in MySQL. Here's a custom PHP function that retrieves the enum values:
<code class="php">function get_enum_values( $table, $field ) { $type = fetchRowFromDB( "SHOW COLUMNS FROM {$table} WHERE Field = '{$field}'" )->Type; preg_match("/^enum\(\'(.*)\'\)$/", $type, $matches); $enum = explode("','", $matches[1]); return $enum; }</code>
This function strips the quotes from the enum values before returning them:
<code class="php">$enum_values = get_enum_values( 'my_table', 'my_field' );</code>
The above is the detailed content of How to Populate Dropdowns Dynamically with Enum Values from a MySQL Database?. For more information, please follow other related articles on the PHP Chinese website!