如何在php中获取sql数据库表名及其数据列表的json编码

如何在php中获取sql数据库表名及其数据列表的json编码,php,Php,如何列出sql数据库中的表名和每个表的表列,然后在PHP中获得结果的json编码? 以下是显示表格的代码: $result = mysql_query("show tables"); // run the query and assign the result to $result while($table = mysql_fetch_array($result)) { // go through each row that was returned in $result echo($tabl

如何列出sql数据库中的表名和每个表的表列,然后在PHP中获得结果的json编码? 以下是显示表格的代码:

$result = mysql_query("show tables"); // run the query and assign the result to $result
while($table = mysql_fetch_array($result)) { 
// go through each row that was returned in $result
echo($table[0] . "<BR>");    // print the table that was returned on that row.
}
$result=mysql_查询(“显示表”);//运行查询并将结果分配给$result
而($table=mysql\u fetch\u数组($result)){
//检查$result中返回的每一行
echo($table[0]。“
”);//打印该行返回的表。 }
您可以创建一个数组/对象并将数据添加到其中。要获得json结果,只需在数组/对象上调用
json\u encode

下面是我要做的:

// Create an object
$results = new stdClass();

// Get all tables
$result = mysql_query("show tables");

// Always check if the query returned anything to prevent possible errors
if(mysql_affected_rows() > 0) {
    // Loop through each table
    while($table = mysql_fetch_assoc($result)) { 
        // Get the columns in the table
        $resultColumns = mysql_query("show columns from ".$table);

        if(mysql_affected_rows() > 0) {
            // Columns found. Create a new property in the object and assign the columns to it
            $tableColumns = mysql_fetch_assoc($resultColumns);
            $results[$table] = $tableColumns;
        }
        else {
            // No columns found. Create a new property in the object and assign a blank array.
            $results[$table] = [];
        }
    }
}
现在,我们可以使用
json\u encode($results)
以json的形式返回数据。

作为补充说明,我希望使用mysqli,而不是mysql(因为它现在已经贬值了)。它的语法基本上是完全相同的,但是在大多数情况下需要将连接变量作为第一个参数传递。因此,使用创建数据库/连接类并调用这些方法将非常有用,而不是直接调用
mysql
mysqli
函数。 请看这里: 这里(举个例子):

注意:这是伪代码,未经测试,但应该可以。如果您需要任何帮助,请告诉我。

$resultColums=mysqli\u query($con,“显示来自“$table”的列);注意:数组到字符串的转换和$results[$table]=[];我明白了,致命的错误:未捕获的错误。无法将stdClass类型的对象用作数组。帮我解决这些问题