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

我创建了这个函数来获取有关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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值