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

Tho*_*asK 3 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  */
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

<?=sql::showTables(true)?>
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述
(我从上面的代码中删除了所有的CSS样式)

还行吧.但我还想得到,至少,类型,长度和评论(如果有的话).

当我写这个问题时,我只是尝试getColumnMeta()将列放入foreach-loop,但是这并没有像预期的那样工作:

    $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'].')';
    }
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述 在此输入图像描述

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

提前致谢.

Kev*_*vin 6

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

SHOW FULL COLUMNS FROM table_test // with FULL option
Run Code Online (Sandbox Code Playgroud)

简单的例子:

$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);
Run Code Online (Sandbox Code Playgroud)

  • 谷歌和我多年来已经达成了相互理解/协议,*自诞生以来*.它给了我我想要的东西,它看到我回来,*每当.*;)我只是不点击他们的广告. (2认同)