使用PHP显示MySQL数据库中的所有表?如何获取表格至 OP

2022-08-30 12:37:55

我正在尝试显示数据库中的所有表。我试过这个:

$sql = "SHOW TABLES";
$result = $conn->query($sql);
$tables = $result->fetch_assoc();
foreach($tables as $tmp)
{
    echo "$tmp <br>";
}

但它只给了我一个表名,我知道有2个。我做错了什么?


答案 1

如何获取表格

1.SHOW TABLES

mysql> USE test;
Database changed
mysql> SHOW TABLES;
+----------------+
| Tables_in_test |
+----------------+
| t1             |
| t2             |
| t3             |
+----------------+
3 rows in set (0.00 sec)

2.SHOW TABLES IN db_name

mysql> SHOW TABLES IN another_db;
+----------------------+
| Tables_in_another_db |
+----------------------+
| t3                   |
| t4                   |
| t5                   |
+----------------------+
3 rows in set (0.00 sec)

3. 使用信息架构

mysql> SELECT TABLE_NAME
       FROM information_schema.TABLES
       WHERE TABLE_SCHEMA = 'another_db';
+------------+
| TABLE_NAME |
+------------+
| t3         |
| t4         |
| t5         |
+------------+
3 rows in set (0.02 sec)

至 OP

你只抓取了1行。修复如下:

while ( $tables = $result->fetch_array())
{
    echo $tmp[0]."<br>";
}

我认为,information_schema会比SHOW TABLES

SELECT TABLE_NAME
FROM information_schema.TABLES 
WHERE TABLE_SCHEMA = 'your database name'

while ( $tables = $result->fetch_assoc())
{
    echo $tables['TABLE_NAME']."<br>";
}

答案 2

试试这个:

SHOW TABLES FROM nameOfDatabase;

推荐