php学习笔记:输出数据库所有字段名

来源:互联网 发布:java方法的概念 编辑:程序博客网 时间:2024/06/01 10:21

因为要经常查询数据库的字段,所以上网查询了一下php 关于读取数据库的表格的字段名。

由于字段名所采取是大写,实现的过程需要转换驼峰式。因此根据这个需求来拼接了一份php代码

基础思路:遍历当前数据库的表,对应查询数据库的字段名。

这里通过两个sql 语句

//显示所有的表名
SHOW TABLES FROM $dbname

//显示表的字段名
SHOW FULL COLUMNS FROM $name

接下来,就是输出的问题了,至于怎样输出就看需要什么内容。
由于是驼峰式,找了一个

<?php$dbname = "dbtest";//选择数据库header("Content-type: text/html; charset=utf-8");      $conn = mysql_connect("localhost", "root", "");mysql_select_db($dbname, $conn);// 检测连接if (!$conn) {    die("Connection failed: " . $conn->connect_error);} mysql_query("set names 'utf8'");$sql = "SHOW TABLES FROM $dbname";$result = mysql_query($sql);while ($row = mysql_fetch_row($result)) {  echo  "=============".$row[0]."<br>";     showAll($row[0],$conn);  echo  "=============" ;  echo "<br>";}function showAll($name,$conn){    $rescolumns = mysql_query("SHOW FULL COLUMNS FROM $name",$conn) ;while($row = mysql_fetch_array($rescolumns)){ // print_r($row)  $item =  lcfirst(convertUnderline3(strtolower($row['Field'])));   $item = "<div style='display:flex;flex-diretion:row;height;'><p style='width:200px;margin:0;padding:0;'>$item</p> <p style='text-align:right;width:400px; display: inline-block;margin:0;padding:0;'>". $row['Comment']."</p></div>";  echo $item;  //echo '字段名称:'.$row['Field'].'类型:'.$row['Type'].'-注释:'.$row['Comment'];  echo '<br/>'; // print_r($row);}} function convertUnderline3 ( $str , $ucfirst = true){    $str = ucwords(str_replace('_', ' ', $str));    $str = str_replace(' ','',lcfirst($str));     return $ucfirst ? ucfirst($str) : $str;}?>

参考资料如下:

mysql 表语句
http://www.php.net/manual/en/function.mysql-list-tables.php
http://www.w3school.com.cn/php/php_mysql_where.asp

使用PHP把下划线分隔命名的字符串 转换成驼峰式命名方式 , 把下划线后面的第一个字母变成大写
http://www.cnblogs.com/sajanray/archive/2015/07/14/4645259.html

utf-8中文编码问题
http://www.jb51.net/article/71638.htm

0 0