我正在创建一个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 :(得分: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';