使用PHP显示MySQL数据库中的所有表?

时间:2013-11-25 01:41:53

标签: php mysql database

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

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

但它只给我一个我知道的数据库中的一个表名2.我做错了什么?

5 个答案:

答案 0 :(得分:76)

如何获取表格

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

你只拿了一排。修理如下:

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

答案 1 :(得分:8)

试试这个:

SHOW TABLES FROM nameOfDatabase;

答案 2 :(得分:2)

SHOW TABLE_NAME无效。试试SHOW TABLES

TD

答案 3 :(得分:0)

SHOW TABLES仅列出给定数据库中的非TEMPORARY表。

https://dev.mysql.com/doc/refman/5.0/en/show-tables.html

答案 4 :(得分:-1)

<?php
$dbname = 'mysql_dbname';
if (!mysql_connect('mysql_host', 'mysql_user', 'mysql_password')) {
echo 'Could not connect to mysql';
exit;
}
$sql = "SHOW TABLES FROM $dbname";
$result = mysql_query($sql);
if (!$result) {
echo "DB Error, could not list tables\n";
echo 'MySQL Error: ' . mysql_error();
exit;
}
while ($row = mysql_fetch_row($result)) {
echo "Table: {$row[0]}\n";
}
mysql_free_result($result);
?>
//Try This code is running perfectly !!!!!!!!!!