PHP获取mysql表信息函数

标签 php mysql mysqli

我正在创建一个 PHP 函数来返回 mysql 数据库表信息的数组。我是 php 编码的新手,正在寻找更有效的方法来完成我所做的同样的事情,因为我的方法似乎不是很有效。这是使用 mysql join 语句的好地方吗?

这是我的函数。

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;
}

感谢您的任何意见:)

最佳答案

您可以只查询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';

关于PHP获取mysql表信息函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12440119/

相关文章:

php - 使用 WordPress 登录凭据的外部应用程序登录

php - vtiger 6 空白(白色)页面导入

mysql - 如何连接到 mysql 并在 Jenkins 自由式作业中传递凭据

php - Magento PHP fatal error : Class 'XXXXXX' not found in Mage. php 第 516 行

php - 如何让 PHP 理解 * 数组或函数参数的 splat 运算符(3 点 ...)?

mysql - 查找具有相同列值的行

mysql - 为什么MySQL在执行这个查询时不使用索引?

php - MySQLi count(*)始终返回1

php - 我必须阅读并显示存储在数据库中的古吉拉特语字体

php - mysqli 中的持久连接如何工作?