我创建了这个函数来获取有关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)?>
(我从上面的代码中删除了所有的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'].')';
}
你可以看到差异..
有谁知道另一种方法吗?得到类型,长度和评论.
提前致谢.
解决方法:
如果要在该特定表上选择注释列信息,可以使用:
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 '
';
print_r($results);
标签:php,mysql,pdo,metadata
来源: https://codeday.me/bug/20190824/1713433.html