Home >Backend Development >PHP Tutorial >How to Populate Dropdowns Dynamically with Enum Values from a MySQL Database?

How to Populate Dropdowns Dynamically with Enum Values from a MySQL Database?

DDD
DDDOriginal
2024-10-29 06:06:31572browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn