2012-09-15 61 views
2

我正在PHP函数中返回一个mysql数据库表的信息数组。我是新来的编码在PHP中,我正在寻找更有效的方式来做同样的事情,因为我的方法似乎不是很有效。这会是一个使用mysql连接语句的好地方吗?PHP获取mysql表信息函数

这是我的功能。

public static function getAllTables() 
{ 
    // Get an array of all the tables in the database 
    $sql = "SHOW TABLES"; 

    //this makes a connection to mysql database using mysqli 
    $mysqlConnection = new CMySqlConnection(); 
    $result = $mysqlConnection->mysqli->query($sql); 
    $tablesArray = array(); 
    while($row = $result->fetch_row()) { 

     $tablesArray[$row[0]]=array(); 

    } 

    $result->close(); 

    //Get an array of all the table names in database 
    $arrayKeys = array_keys($tablesArray); 

    //foreach table get the column's info 
    foreach($arrayKeys as $key){ 
     $sql=" SHOW COLUMNS from " . $key; 
     $result = $mysqlConnection->mysqli->query($sql); 
     for($i = 0; $row = $result->fetch_row(); $i++) { 

      //format the array to use a descriptive key rather than a number 
      $row['columnName'] = $row[0]; 
      $row['type'] = $row[1]; 
      $row['null'] = $row[2]; 
      $row['key'] = $row[3]; 
      $row['default'] = $row[4]; 
      $row['extra'] = $row[5]; 

      unset($row[0]); 
      unset($row[1]); 
      unset($row[2]); 
      unset($row[3]); 
      unset($row[4]); 
      unset($row[5]); 

      // put the column info into the tables array 
      $tablesArray[$key][$i] = $row; 
     } 
     $result->close(); 
    } 


    $mysqlConnection->Disconnect(); 

    // return the tables array 
    return $tablesArray; 
} 

感谢任何输入:)

+0

+1对于良好被问到的问题,以及使用和mysqli库。我厌倦了在这里看到使用旧的mysql_xxx funcs的人,所以看到不是的人很爽。 – Spudley

回答

2

您可以直接查询INFORMATION_SCHEMA。它们是包含有关数据库的信息虚拟表:http://dev.mysql.com/doc/refman/5.5/en/information-schema.html

SELECT TABLE_SCHEMA, TABLE_NAME FROM INFORMATION_SCHEMA.TABLES; 

SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA='schema' AND TABLE_NAME='table'; 
+0

非常感谢。将第二个查询更改为“SELECT TABLE_NAME,COLUMN_NAME,COLUMN_DEFAULT,IS_NULLABLE,COLUMN_TYPE,COLUMN_KEY,EXTRA FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA ='schema'AND TABLE_NAME ='table'”给了我期待的结果。 – Robert

+0

P.S.我会upvote,但我还没有足够高的代表:P – Robert

+0

+1的一个很好的答案。 @罗伯特 - 我已经提出了你的问题,所以现在你有足够的代表upvote答案:)享受你的新发现的权力,但明智地使用它们! – Spudley