Php 如何使用PDO获取MySQL数据库中列的类型、长度和注释?
我创建此函数是为了获取MySQL数据库中表及其对应列的信息:Php 如何使用PDO获取MySQL数据库中列的类型、长度和注释?,php,mysql,pdo,metadata,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
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)?>
您可以看到差异。有人知道另一种方法吗?获取类型、长度和注释
提前感谢。如果您想选择该特定表格上的
注释
列信息,您可以使用:
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);
$db=newpdo('mysql:host=localhost;dbname=db_NAME;charset=utf8','username','password');
$db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_异常);
$query=$db->query('SHOW FULL COLUMNS FROM table_test');
// ^
$results=$query->fetchAll(PDO::FETCH_ASSOC);
回声';
打印(结果);
实际上,我从来都不知道这里的FULL
选项,并且一直在深入研究这方面的信息。谢谢真幸运!我在这里找到了它-SHOW[FULL]COLUMNS{FROM|IN}tbl_name[{FROM|IN}db_name][LIKE'pattern'| WHERE expr]
“FULL
关键字使输出包含列排序规则和注释,以及您对每列拥有的特权。”搜索/研究一直是我最喜欢做的事情;)有时花几个小时,甚至几天,是我不介意做的事情;如果需要的话。@ThomasK事实上我的第一个发现不是这个,而是在信息模式上,我实际上偶然发现了joomla论坛的这个答案哈哈,但是fred在找到这个答案时甚至没有出一点汗,就像往常一样锋利,呵呵,无论如何我很高兴这个答案帮助了Google,我已经有了多年的相互理解/协议,事实上,自从它诞生以来。它给了我想要的,它看到我回来,无论何时我只是不点击他们的广告。
$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);