提问人:ThomasK 提问时间:10/2/2014 更新时间:10/2/2014 访问量:2331
如何使用PDO获取MySQL数据库中列的类型、长度和注释?
How can I get the type, length and comment about columns in MySQL database using PDO?
问:
我创建了这个函数来获取有关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样式)
这没关系。但我也想至少得到类型、长度和评论(如果有的话)。
当我写这个问题时,我只是尝试将 -loop 放在列内,但这并没有像预期的那样工作: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'].')';
}
你可以看到区别..
有谁知道另一种方法?获取类型、长度和注释。
提前致谢。
答:
7赞
Kevin
10/2/2014
#1
如果要选择该特定表的列信息,可以使用: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);
评论
1赞
Michael Berkowski
10/2/2014
实际上,我从来不知道这里的选项,并且一直在为这些东西挖掘information_schema。谢谢!FULL
1赞
Funk Forty Niner
10/2/2014
确实是幸运的发现!我在这里找到了它 dev.mysql.com/doc/refman/5.0/en/show-columns.html - - “FULL
关键字使输出包括列排序规则和注释,以及您对每列拥有的权限。”SHOW [FULL] COLUMNS {FROM | IN} tbl_name [{FROM | IN} db_name] [LIKE 'pattern' | WHERE expr]
1赞
Funk Forty Niner
10/2/2014
搜索/研究一直是我最喜欢做的事情;)有时花几个小时,甚至几天是我不介意做的事情;如果需要。
1赞
Kevin
10/2/2014
@ThomasK实际上我的第一个发现不是这个,而是在信息模式上,我实际上偶然发现了一个 joomla 论坛来寻找这个答案哈哈,但弗雷德甚至没有费力地发现,像往常一样锋利如矛尖呵呵,无论如何我很高兴这个答案有所帮助
2赞
Funk Forty Niner
10/2/2014
谷歌和我多年来一直保持着相互理解/协议,实际上从它诞生以来。它给了我我想要的东西,它看到我回来,无论何时。 ;)不过,我只是不点击他们的广告。
评论