To retrieve all tables from a database using PHP, you can use an SQL query to select all table names from a specific database and store the results in an array. The following example demonstrates how to query all tables in a database using PHP and MySQL:
<?php
// 定义数据库连接信息
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";
// 创建数据库连接
$conn = new mysqli($servername, $username, $password, $dbname);
// 检查连接是否成功
if ($conn->connect_error) {
die("连接失败:" . $conn->connect_error);
}
// 查询数据库中所有表名
$sql = "SHOW TABLES";
$result = $conn->query($sql);
// 将表名存储在数组中
$tables = array();
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$tables[] = $row['Tables_in_'.$dbname];
}
}
// 输出表名
echo "该数据库中有以下表:";
foreach ($tables as $table) {
echo $table . "<br>";
}
// 关闭数据库连接
$conn->close();
?>In the above code, we first define the database connection details—including the host name, username, password, and database name. Then, we establish a database connection and use the SQL statement "SHOW TABLES" to query all table names in the database. The query results are stored in an array, and all table names are then printed out.
Finally, we close the database connection to release resources.
function encapsulation
This function accepts four parameters: host name, username, password, and database name. It uses these parameters to establish a database connection and executes the SQL statement "SHOW TABLES" to query all table names in the database. The query results are stored in an array, and the database connection is closed at the end of the function. Finally, the function returns an array containing all the table names.
You can use this function as follows:
// 定义数据库连接信息
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";
// 调用函数获取所有表名
$tables = getAllTables($servername, $username, $password, $dbname);
// 输出表名
echo "该数据库中有以下表:";
foreach ($tables as $table) {
echo $table . "<br>";
}