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

因为要经常查询数据库的字段,所以上网查询了一下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
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值