Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

phalcon get enum values

Tags:

php

mysql

phalcon

I'm working with database with a lot of columns with 'enum' and 'set' type. My point is to get values of column in Phalcon controller. I found some snippets, but nothing in Phalcon and when I tried to execute them it seems that Phalcon have some problems.

public function getEnumValues(){
    $sql  = "SHOW COLUMNS FROM profiles LIKE 'eyes_color'";

    $query = new \Phalcon\Mvc\Model\Query($sql, $this->getDI());
    $result = $query->execute();

    return $result;
}

Returns:

Syntax error, unexpected token IDENTIFIER(SHOW), near to ' COLUMNS FROM profiles LIKE 'eyes_color'', when parsing: SHOW COLUMNS FROM profiles LIKE 'eyes_color'

Approach 2:

public function getEnumValues(){
    $sql = "SELECT COLUMN_TYPE FROM COLUMNS WHERE TABLE_NAME = 'profiles' AND COLUMN_NAME = 'hair_color'";

    $query = new \Phalcon\Mvc\Model\Query($sql, $this->getDI());
    $result = $query->execute();

    return $result;
}

Returns:

Model 'COLUMNS' could not be loaded

I would be grateful for any help.

like image 439
Rocket Avatar asked Feb 15 '26 23:02

Rocket


1 Answers

This is working version for your needs:

$config = $this->getDI()->get('config');
$pdo    = new \Phalcon\Db\Adapter\Pdo\Mysql([
    "host"     => $config->database->host,
    "username" => $config->database->username,
    "password" => $config->database->password,
    "dbname"   => $config->database->dbname,
]);
$sql = "
    SELECT TRIM(TRAILING ')' FROM SUBSTRING(COLUMN_TYPE,6)) AS enum_list
    FROM information_schema.COLUMNS
    WHERE TABLE_SCHEMA='my_db_name'
        AND TABLE_NAME='my_table_name'
        AND COLUMN_NAME='my_column_name'
";
$result    = $pdo->query($sql)->fetch();
$enumArray = array();
if (!empty($result['enum_list'])) {
    $enumArray = explode(',', $result['enum_list']);
    foreach ($enumArray as &$value) {
        $value = trim($value, "'");
    }
}
echo "<pre>"; var_dump($enumArray); die;
like image 112
PVGrad Avatar answered Feb 18 '26 11:02

PVGrad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!