December 9, 2013

How to get available values for SET field?

Kirzilla’s Question:

Is there any way to get available values for SET field in table?

Thank you.

You can retrieve the possible values for a SET field using DESCRIBE myTableName mySetColumn or SHOW COLUMNS FROM myTableName LIKE mySetColumn:

  mysql> DESCRIBE myTableName mySetColumn;
  +-------+-------------------------------------------+------+-----+---------+-------+
  | Field | Type                                      | Null | Key | Default | Extra |
  +-------+-------------------------------------------+------+-----+---------+-------+
  | myset | set('Travel','Sports','Dancing','Dining') | YES  |     | NULL    |       |
  +-------+-------------------------------------------+------+-----+---------+-------+

Informative article here, manual here.

Here is how to get the possible values of SET using PDO extension.

function get_set($table, $column)
{

    global $db; //PDO DB Handler

    $sql = "SHOW COLUMNS FROM $table LIKE :column";
    $stmt = $db -> prepare($sql);

    $stmt -> bindParam(":column", $column, PDO::PARAM_STR, 50);

    try {
        $result = $stmt -> execute();
        $row = $stmt -> fetch(PDO::FETCH_ASSOC);
        $set = $row['Type'];
        $set  = substr($set,5,strlen($set)-7);
        // Split into an array.
        return preg_split("/','/",$set);
    } catch (PDOException $e) {
        echo $e -> getMessage();
        return false;
    }

}

[Source]

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!