php mysql 数据表获取字段名,长度,信息

 更新时间:2016年11月25日 16:38  点击:2059
强大的php可以利用mysql交互的相关函数可以获取数据表的字段信息,如可以获取数据表获取字段名,字段长度,字段信息等。

$hostname="localhost";         //定义连接到的mysql服务器名
$username="root";          //定义用于连接的用户名
$password="";           //定义用于连接的密码
$link=mysql_connect($hostname,$username,$password);   //打开mysql连接
$db_list=mysql_list_dbs($link);        //列出数据库教程
$rows=mysql_num_rows($db_list);       //取得返回结果数
$i=0;
while($i<$rows)           //通过循环遍历结果集并赋值给对象
{
  echo mysql_db_name($db_list,$i)."n";      //输出对象内容
  echo "<p>n";
  $i++;
}
mysql_close($link);          //关闭mysql连接

//返回列的长度

$sql_str="select * from friends where id=1";     //定义sql语句
$result=mysql_query($sql_str);        //执行sql语句
$re_a=mysql_fetch_array($result);
$re_len=mysql_fetch_lengths($result);
for($i=0;$i<count($re_len);$i++)
{
  echo "返回结果的第".$i."列的长度为:".$re_len[$i];
  echo "<p>";
}
mysql_close($link); 

//获取字段信息

$result=mysql_query("select * from friends");     //执行sql查询
/*获取字段信息*/
$i=0;
while($i<mysql_num_fields($result))       //循环读取结果数
{
  $i++;
  echo "第".$i."列的信息:<br/>n";
  $meta=mysql_fetch_field($result);       //获取字段信息
  if(!$meta)           //如果值不存在
  {
    echo "no information available<br/>n";     //输出无可用信息
  }
  echo "<pre>
blob:     $meta->blob
max_length:   $meta->max_length
multiple_key:  $meta->multiple_key
name:        $meta->name
not_null:      $meta->not_null
numeric:      $meta->numeric
primary_key:  $meta->primary_key
table:         $meta->table
type:         $meta->type
unique_key:  $meta->unique_key
unsigned:    $meta->unsigned
zerofill:       $meta->zerofill
</pre>";            //结束去格式输出

//mysql_field_flags() 函数从结果中取得和指定字段关联的标志。
$re_field=mysql_field_flags($result,0);
$flag=explode(" ",$re_field);
print_r($flag);
$re_field=mysql_field_flags($result,1);
$flag=explode(" ",$re_field);

//列名

$result=mysql_query($sql_str);        //执行sql语句
$re_name=mysql_field_name($result,0);      //获取第一个字段的名称
echo "第一个字段的名称为:".$re_name;
echo "<p>";
$re_name=mysql_field_name($result,1);      //获取第二个字段的名称
echo "第二个字段的名称为:".$re_name;
echo "<p>";
$re_name=mysql_field_name($result,2);      //获取第三个字段的名称
echo "第三个字段的名称为:".$re_name;
echo "<p>";
$re_name=mysql_field_name($result,3);      //获取第四个字段的名称
echo "第四个字段的名称为:".$re_name;
echo "<p>";
$re_name=mysql_field_name($result,4);      //获取第五个字段的名称
echo "第五个字段的名称为:".$re_name;
echo "<p>";

   function mysql教程connector() : 类的构造函数,定义和包含配置信息
   function connectmysql()   : 打开数据库教程连接
   function close()          : 关闭数据库连接        
   function returnsql($sql)  : 执行一条语句,返回一行的数组
   function executesql($sql) : 执行一段查询,返回是否成功
   function returndb($sql)   : 执行查询,返回数据集
   function selectlimit($sql,$offset_b,$offset_n=0)
                             : 分页查询,返回数据集 参数(sql语句,开始位置,读取行数)
   function datearray($sql,$startid,$endid)
                             : 分页查询,返回二维数组 参数(sql语句,开始位置,读取行数)
   function getarray($sql)   : 执行两个字段的查询,返回一个数组,格式 array[row["0"]]=>row["1"]
  
 
*/

 

class mysqlconnector
{
/* public: 数据库连接参数 */
     var $dbhost;        //服务器地址
     var $dbname;        //数据库名称
     var $dbusername;    //连接账号
     var $dbpassword;    //连接密码
  var $setnames;      //数据库编码

   function mysqlconnector()         //构造函数,数据库链接配置
   {
        $this->dbname = "xixia";
        $this->dbhost = "localhost";
        $this->dbusername = "root";
        $this->dbpassword = "123456";
        $this->setnames="gbk";
   }

   function connectmysql()       //链接数据库,返回活动连接
   {
        $openconn = mysql_pconnect($this->dbhost,$this->dbusername,$this->dbpassword ) or die("连接数据库错误,请检查配置!");
        mysql_query("set names '".$this->setnames."'",$openconn);
        mysql_select_db($this->dbname,$openconn);
        return $openconn;
   }
  
    /*
    *
    *执行查询语句,返回某一行的数组
    */

    function returnsql($sql)
 {
  $array_result="";
 
  //mysql_unbuffered_query
     $db_result=mysql_query($sql,$this->connectmysql());
     if($db_result){
   $array_result=mysql_fetch_array($db_result);   
     }
  mysql_free_result($db_result);   //释放记录集
  return $array_result;
   
    }
 
 /*
 *
 *执行查询语句,返回数据
 *
 */
 
 function returndb($sql)   
 {
     $db_result=mysql_query($sql,$this->connectmysql());
  return $db_result;
  
 }
  
 /*
 *
 *执行查询语句,返回某两列的数组,主要用于下拉框,前一列是values,后一列是option
 *
 */
 
  function getarray($sql)    
 {
  $array_result=array();
 
     $db_result=mysql_query($sql,$this->connectmysql());
     if($db_result){
     while($row=mysql_fetch_row($db_result))
     {
         $array_result[$row[0]]=$row[1];
     }
     }
  
  return $array_result;
   
    }

    /*
    *
    *执行一条sql语句,返回执行是否成功
    *
    */

    function executesql($sql)    
 {   
  //$sql = str_replace("","\",$sql);
     $result=mysql_query($sql,$this->connectmysql());
     if(!$result){
      echo "<!--出错了:" . $sql."-->";
      return false;
     }else{
      return true; 
  }
    }
 
 /*
 
 分页读取sql语句,返回纪录集,
 参数分别为sql语句,开始行数,读取条数(传递2哥参数时,开始行数即为读取条数)
 */
 
 function selectlimit($sql,$offset_b,$offset_n=0)   
 {
 
     $result="";
  $this->checklink($sql);
  if(!$offset_n){
   $limit = " limit ".$offset_b;
  }else{
   $limit = " limit ".$offset_b.",".$offset_n; 
  }
  $sql.=$limit;
//  echo "<br>";
//  echo $sql;
   
  $result = $this->returndb($sql);
  return $result;
 }
 
/*
*
*将数据集转化成数组
*
*/ 
    function datearray($sql,$startid,$endid)
 {
    $array_result=array();
    $db_result=$this->selectlimit($sql,$startid,$endid);           //根据sql语句读取数据集
   
    if($db_result){                                //数据集存在
        $i=0;
     while($row=mysql_fetch_row($db_result))    //循环填充数组
     {
         $array_result[$i]=$row;
      $i++;
     }
     }
  
  return $array_result;
 
 }
  
 /*
 *
 *关闭链接
 *
 */
    function close()     
 {
        if($this->linkid!=null)
        {
            mysql_close($this->linkid);
            unset($this);
        }
 }
   
}
/*

*使用案例:
  $conn= new mysqlconnector();   //实例化
  $db = &$conn; 
 
  $db->returnsql($sql)     //执行查询
 


  */

这是一款php中的mysql数据库连接文件代码,如果你正在找这样功能的代码,可以进来看看,非常完整文件

class mysql {
 private $db_host;     //主机地址
 private $db_user;     //用户名
 private $db_pass;     //连接密码
 private $db_name;     //名称
 private $db_charset;  //编码

 private $conn;
 private $query_id;   //用于判断sql语句是否执行成功
 private $result;     //结果集
 private $num_rows;   //结果集中行的数目,仅对select有效
 private $insert_id;  //上一步 insert 操作产生的 id

// 构造/析构函数
 function __construct ($db_host,$db_user,$db_pass,$db_name,$db_charset,$conn) {
 $this->db_host = $db_host ;
 $this->db_user = $db_user ;
 $this->db_pass = $db_pass ;
 $this->db_name = $db_name ;
 $this->db_charset = $db_charset ;
 $this->conn = $conn ;
 $this->connect();
 }

 function __destruct () {
 @mysql_close($this->conn);
 }

// 连接/选择数据库
 public function connect () {
 if ($this->conn == 'pconn') {
  @$this->conn = mysql_pconnect($this->db_host,$this->db_user,$this->db_pass);
 } else {
  @$this->conn = mysql_connect($this->db_host,$this->db_user,$this->db_pass);
 }
 if (!$this->conn) {
  $this->show_error('数据库-连接失败:用户名或密码错误!');
 }
 if (!@mysql_select_db($this->db_name,$this->conn)) {
  $this->show_error("数据库-选择失败:数据库 $this->db_name 不可用");
 }
 mysql_query("set names $this->db_charset");
 return $this->conn;
 }

// query方法
 public function query ($sql) {
 if ($this->query_id) $this->free_result();
 $this->query_id = @mysql_query($sql,$this->conn);
 if (!$this->query_id) $this->show_error("sql语句 <b>"$sql"</b> 执行时遇到错误");
 return $this->query_id;
 }

// 查询所有
 public function findall ($table_name) {
 $this->query("select * from $table_name");
 }

// mysql_fetch_array
 public function fetch_array () {
 if ($this->query_id) {
  $this->result = mysql_fetch_array($this->query_id);
  return $this->result;
 }
 }

// ......

 public function fetch_assoc () {
 if ($this->query_id) {
  $this->result = mysql_fetch_assoc($this->query_id);
  return $this->result;
 }
 }

 public function fetch_row () {
 if ($this->query_id) {
  $this->result = mysql_fetch_row($this->query_id);
  return $this->result;
 }
 }

 public function fetch_object () {
 if ($this->query_id) {
  $this->result = mysql_fetch_object($this->query_id);
  return $this->result;
 }
 }

// 获取 num_rows
 public function num_rows () {
 if ($this->query_id) {
  $this->num_rows = mysql_num_rows($this->query_id);
  return $this->num_rows;
 }
 }

// 获取 insert_id
 public function insert_id () {
 return $this->insert_id = mysql_insert_id();
 }

// 显示共有多少张表
 public function show_tables () {
 $this->query("show tables");
 if ($this->query_id) {
  echo "数据库 $this->db_name 共有 ".$this->num_rows($this->query_id)." 张表<br/>";
  $i = 1;
  while ($row = $this->fetch_array($this->query_id)){
    echo "$i -- $row[0]<br/>";
    $i ++;
  }
 }
 }

// 显示共有多少个数据库
 public function show_dbs(){
 $this->query("show databases");
 if ($this->query_id) {
  echo "共有数据库 ".$this->num_rows($this->query_id)." 个<br/>";
  $i = 1;
  while ($this->row = $this->fetch_array($this->query_id)){
    echo "$i -- ".$this->row[database]."<br />";
    $i ++;
  }
 }
 }

// 删除数据库:返回删除结果
 public function drop_db ($db_name='') {
  if ($db_name == '') {
   $db_name = $this->db_name;//默认删除当前数据库
  $this->query("drop database $db_name");
 }else {
  $this->query("drop database $db_name");
 }
 if ($this->query_id) {
  return "数据库 $db_name 删除成功";
 }else {
  $this->show_error("数据库 $db_name 删除失败");
 }
}

// 删除数据表:返回删除结果
 public function drop_table ($table_name) {
 $this->query("drop table $table_name");
  if ($this->query_id) {
  return "数据表 $table_name 删除成功";
 }else {
  $this->show_error("数据表 $table_name 删除失败");
 }

}

// 创建数据库
public function create_db ($db_name) {
 $this->query("create database $db_name");
 if($this->query_id){
  return "数据库 $db_name 创建成功";
 }else {
  $this->show_error("数据库 $db_name 创建失败");
 }
}

// 获取数据库版本
 public function get_info(){
 echo mysql_get_server_info();
 }

// 显示错误信息
 public function show_error ($msg) {
 $errinfo = mysql_error();
 echo "错误:$msg <br/> 返回:$errinfo<p>";
 }

// 释放内存
 public function free_result () {
 if ( @mysql_free_result($this->query_id) )
 unset ($this->result);
 $this->query_id = 0;
 }

} // end class

 

odbc_connect() 函数用于连接到 ODBC 数据源。该函数有四个参数:数据源名、用户名、密码以及可选的指针类型参数。

odbc_exec() 函数用于执行 sql 语句

$db_user="dbuser";         //定义连接用户名
$db_pass="dbpass";         //连接用户对应的密码
$dsn="dsn";          //定义dsn资料来源
if(odbc_connect($dsn,$db_user,$db_pass))    //对odbc数据源进行连接
{
  echo "成功连接到odbc数据源";      //如果成功输出内容
}
else
{
  echo "连接到odbc时出现问题!";     //如果失败输出内容
}

odbc_close_all();        //关闭所有打开的连接
echo "所有打开的odbc连接都已经被关闭!";   //执行函数后输出内容


看一个更高级的与主机连接

$db_host="server.mynetwork";        //定义主机名
$db_user="dbuser";          //定义连接用户名
$db_pass="dbpass";          //定义用户对应的密码
$dsn="dsn";           //定义dsn
$result=odbc_pconnect($dsn,$db_user,$db_pass);    //打开持续有效的odbc连接
if($result)            //对结果进行判断
{
  echo "打开一个持续有效的连接";       //成功执行输出内容
}
echo "<br>";
if(odbc_close($result))         //尝试关闭连接
{
  echo "关闭了?";          //如果成功关闭输出内容
}
else
{
  echo "不能关!";          //如果关闭失败输出内容
}

查询数据库教程存

数据源进行连接

$my_sql="select * from usertable";      //定义sql语句
$result=odbc_do($myconn,$my_sql);     //执行sql语句
echo odbc_num_rows($result);
echo "<table border="1">n";
echo "<tr>n";
echo "<td>id号</td>n";
echo "<td>name</td>n";
echo "<td>address</td>n";
echo "</tr>n";
while(odbc_fetch_row($result))
{
  echo "<tr>n";
  echo "<td>".odbc_result($result,1)."</td>n";
  echo "<td>".odbc_result($result,2)."</td>n";
  echo "<td>".odbc_result($result,3)."</td>n";
  echo "</tr>n";
}
echo "</table>";


一些相关

odbc_free_result($result);        //释放执行sql语句占用的内存
echo "已经成功释放结果集占用的内存!";
odbc_rollback($myconn)取消所有未提交的操作
odbc_commit($myconn) //提交所有未提交的操作
odbc_autocommit($myconn,false);      //禁止自动commit
odbc_columnprivileges($myconn,"dbuser","管理员","usertable","name"); //列出给定表的列和权限
$result=odbc_columns($myconn);      //列出指定表的列的名称
echo odbc_result_all($result); 

在php中连接mysql数据库有二种如有mysql_connect 与mysql_pconnect,一个是软连接,一个是持续连接,两者区别在于一个当页面浏览完自动关闭已经打开的MySQL连接页mysql_pconnect如果不关闭就一直连接。

$hostname="localhost";        //定义连接到的mysql服务器名
$username="root";         //定义用于连接的用户名
$password="";          //定义用于连接的密码
$link=mysql_connect($hostname,$username,$password);  //连接到本地mysql服务器
if($link)           //如果成功连接
{
  echo "成功连接";         //输出内容
}
else            //如果连接失败
{
  echo "连接失败";         //输出内容
}
//mysql_close($link) //关闭已经打开的mysql连接

//mysql_pconnect连接mysql数据库

$link=mysql_pconnect($hostname,$username,$password);  //打开持续性连接
if(!$link)            //如果不能连接
{
  die('不能连接'.mysql_error());        //输出信息
  exit();            //结束所有php操作
}
echo '持续连接成功';

/*
下面看软连接查询数据库内容

*/

$link=mysql_connect($hostname,$username,$password)or die("could not connect:".mysql_error());
//转换编码以支持中文
mysql_query('set   names   gb2312;');
//选择操作库test
mysql_select_db("test")or die("could not select database:".mysql_error());
//执行sql查询,从表中选择名字
$query="select name from friends";
$result=mysql_query($query)or die("query failed:".mysql_error());
//匹配结果集到行循环输出内容
for($i=mysql_num_rows($result)-1;$i>=0;$i--)
{
//移动内部结果的指针,如果没有结果则输内容
  if(!mysql_data_seek($result,$i))
  {
    echo "cannot seek to row $i:".mysql_error()."n";
    continue;
  }
//从查询结果取得一行作为对象
  if(!($row=mysql_fetch_object($result)))
  continue;
//输出结果内容
  echo "$row->name<br/>n";
}
//释放结果集
mysql_free_result($result);

/*
其它操作

$escaped_item=mysql_escape_string($str);    //将字符串转义
printf("escaped string:%sn",$escaped_item);    //输出转义后的结果

$mydb=mysql_list_dbs($link);      //列出数据库
while($result=mysql_fetch_object($mydb))   //通过循环遍历结果集并赋值给对象
{
  echo $result->database."n";      //输出对象内容
  echo "<br>";
}

[!--infotagslink--]

相关文章