从MySQL数据库获取表列表

时间:2019-03-15 04:52:43

标签: php mysql mysqli

我刚刚开始学习php。

我正在尝试从数据库中获取表列表。我尝试过的-

<?php   
    $connection = new mysqli("localhost", "root", "");
    $sql = "SHOW TABLES FROM MyDatabase";
    $result = $connection->query($sql);

    while ($row = $result->fetch_assoc()) {
       echo "Table: {$row[0]}\n"; //error here
    }
?>

但是它不显示表并返回-Notice: Undefined offset: 0。 有帮助吗?

2 个答案:

答案 0 :(得分:1)

尝试用fetch_array()代替fetch_assoc()

fetch_array()返回一个包含数字键和关联字符串(列名)的数组,因此您可以在此处使用$row['column_name']$row[0]

fetch_assoc()处将返回字符串索引键数组,而不返回数字数组,因此在这里您将无法使用$row[0]之类的数字键。

更改下面的代码-

<?php   
    $connection = new mysqli("localhost", "root", "");
    $sql = "SHOW TABLES FROM MyDatabase";
    $result = $connection->query($sql);

    while ($row = $result->fetch_array()) {
       echo "Table: {$row[0]}\n";
    }
?>

答案 1 :(得分:0)

0数组中没有$row索引,因为您正在调用fetch_assoc(),它返回带有关联键的数组。尝试将调用更改为fetch_row(),这将返回一个数字索引的数组,或者更改为fetch_array(),这将返回一个具有数字索引和关联索引的数组。例如

while ($row = $result->fetch_row()) {