PHP获取mysql数据表的字段名称和详细信息的方法
首先我们需要了解下查询mysql数据库/表相关信息的sql语句:
show databases //列出 mysql server 数据库。
show tables [from db_name] //列出数据库数据表。
show create tables tbl_name //导出数据表结构。
show table status [from db_name] //列出数据表及表状态信息。
show columns from tbl_name [from db_name] //列出资料表字段
show fields from tbl_name [from db_name],describe tbl_name [col_name]。
show full columns from tbl_name [from db_name]//列出字段及详情
show full fields from tbl_name [from db_name] //列出字段完整属性
show index from tbl_name [from db_name] //列出表索引。
show status //列出 db server 状态。
show variables //列出 mysql 系统环境变量。
show processlist //列出执行命令。
show grants for user //列出某用户权限
由上述sql语句可以看到,我们可以使用show full columns来列出字段及详情信息,示例代码:
$rescolumns = mysql_query("show full columns from ".tb_name."") ;
while($row = mysql_fetch_array($rescolumns)){
// echo '字段名称:'.$row['field'].'-数据类型:'.$row['type'].'-注释:'.$row['comment'];
// echo '<br/><br/>';
print_r($row);
}
打印结果:
array ( [0] => id [field] => id [1] => char(2) [type] => char(2) [2] => utf8_general_ci [collation] => utf8_general_ci [3] => no [null] => no [4] => pri [key] => pri [5] => [default] => [6] => [extra] => [7] => select,insert,update,references [privileges] => select,insert,update,references [8] => [comment] => )
array ( [0] => title [field] => title [1] => char(50) [type] => char(50) [2] => utf8_general_ci [collation] => utf8_general_ci [3] => yes [null] => yes [4] => [key] => [5] => [default] => [6] => [extra] => [7] => select,insert,update,references [privileges] => select,insert,update,references [8] => 建议存储:标题、姓名等信息 [comment] => 建议存储:标题、姓名等信息 )
array ( [0] => des [field] => des [1] => varchar(255) [type] => varchar(255) [2] => utf8_general_ci [collation] => utf8_general_ci [3] => yes [null] => yes [4] => [key] => [5] => [default] => [6] => [extra] => [7] => select,insert,update,references [privileges] => select,insert,update,references [8] => [comment] => )
…………
补充说明信息:
当然你也可以通过mysql_list_fields — 列出 mysql 结果中的字段。mysql_list_fields() 取得给定表名的信息,参数是数据库名和表名,返回一个结果指针。
但是,mysql_list_fields() 函数已过时。最好用 mysql_query() 来发出一条 show columns from table [like 'name'] 的 sql 语句来代替。详细可参考php帮助文档:php: mysql_list_fields - manua