phpmysqlsqlenums

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


I have set up a coloumn in Mysql:

type: ENUM

Length/Values: '01','02','03','04','05','06','07','08','09','10','11','12'

I'm trying to retrive those values from the DB:

I found another post with the same question but my code didn't work

$type = $mysqli->query( "SHOW COLUMNS FROM {$tableName} WHERE Field = 'type'" )->fetch_object()->Type;
        preg_match('/^enum\((.*)\)$/', $type, $matches);
        foreach( explode(',', $matches[1]) as $value )
        {
             $enum[] = trim( $value, "'" );
        }
        return $enum;

I get type Text Insted of ENUM


Solution

  • You should parse information from information_schema.columns table -

    SELECT
      column_type
    FROM
      information_schema.columns
    WHERE
      table_schema = 'your_schema' AND table_name = 'your_table' AND column_name = 'your_column'
    

    ...another query -

    SELECT
      TRIM(TRAILING ')' FROM TRIM(LEADING '(' FROM TRIM(LEADING 'enum' FROM column_type))) column_type
    FROM
      information_schema.columns
    WHERE
      table_schema = 'your_schema' AND table_name = 'your_table' AND column_name = 'your_column';
    

    There will be something like this - enum('01','02','03'). Parse this string in the php-application.