如何使用PDO获取MySQL数据库中列的类型,长度和注释?

时间:2014-10-02 02:37:29

标签: php mysql pdo metadata

我已创建此函数以在MySQL数据库中获取有关表及其相应列的信息:

class SQL extends DB
{
    public static function showTables($alias='', $table_name='')
    {
        if(empty($alias) || $alias===true){  //  empty = show all tables from all available connections, true = show columns aswell
            foreach(self::get() as $con){  //  get() keeps, among other things, the aliases of all available connections
                $html .= '"'.$con['alias'].'": '.$con['db'];  //  the alias for the connection, and databasename, for the following table(s)
                $tables = self::con($con['alias'])->query('SHOW TABLES')->fetchAll(PDO::FETCH_COLUMN);  //  fetch an array of all tables available through this connection
                foreach($tables as $table){
                    $html .= $table;  //  table name
                    if($alias===true){  //  show columns aswell when this is set to true
                        $columns = self::con($con['alias'])->query('SHOW COLUMNS FROM '.$table)->fetchAll(PDO::FETCH_COLUMN);  //  fetch an array of all column in this table
                        foreach($columns as $column){
                            $html .= $column;  //  column name
                        }
                    }
                }
            }
        } else {
            /*  basically the same code, but limits the result to a defined connection. And table if that is defined  */
        }
    }
}

重要的是要知道此功能是根据我设置和使用PDO连接的方式量身定制的。基本上每个连接都有一个别名,并且通过给定的别名访问连接。但这与我的问题无关。

以下是我如何使用该函数及其产生的内容:

<?=sql::showTables(true)?>

enter image description here
(我已从上面的代码中删除了所有css样式)

这没关系。但我还想得到,至少,类型,长度和评论(如果有的话)。

当我写这个问题时,我刚尝试将getColumnMeta()置于列foreach - 循环中,但这并不像预期的那样有效:

    $columns = self::con($con['alias'])->query('SHOW COLUMNS FROM '.$table)->getColumnMeta(0);
    foreach($columns as $column){
        $meta = self::con($con['alias'])->query('SELECT `'.$column.'` FROM '.$table)->getColumnMeta(0);
        $html .= $meta['name'].' '.$meta['native_type'].'('.$meta['len'].')';
    }

enter image description here enter image description here

你可以看到差异..
有谁知道另一种方法吗?得到类型,长度和评论。

提前致谢。

1 个答案:

答案 0 :(得分:6)

如果要在该特定表格上选择comment列信息,可以使用:

SHOW FULL COLUMNS FROM table_test // with FULL option

简单示例:

$db = new PDO('mysql:host=localhost;dbname=DB_NAME;charset=utf8', 'username', 'password');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = $db->query('SHOW FULL COLUMNS FROM table_test');
                      //  ^
$results = $query->fetchAll(PDO::FETCH_ASSOC);
echo '<pre>';
print_r($results);
相关问题