我只需要知道如何打印出表名和列,我尝试的一切都不起作用,即使这显然很简单。我到处寻找,我找不到任何可以打印出列的内容。有人可以帮忙吗?
答案 0 :(得分:1)
这些的MySQL语法使用命令SHOW
,该命令可用于显示所选数据库(SHOW tables;
)或输出表结构(SHOW tableName;
)中的表。
以下是只要更新连接详细信息(第一行代码),就可以查看当前数据库中的表的功能代码:
$mysqli = new mysqli("server.com", "userName", "password", "dbName");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
$query = "SHOW tables;";
$result = $mysqli->query($query);
/* associative array */
$rows = $result->fetch_all(MYSQLI_ASSOC);
var_export($rows);
$result->free();
/* close connection */
$mysqli->close();
答案 1 :(得分:1)
以下代码应提取您所需的信息。
<?php
$mysqli = new mysqli("hostname", "username", "password", "database");
if($mysqli->connect_errno)
{
echo "Error connecting to database.";
}
// Gather all table names into an array.
$query = "SHOW TABLES";
$result = $mysqli->query($query);
$tables = $result->fetch_all();
// Step through the array, only accessing the first element (the table name)
// and gather the column names in each table.
foreach($tables as $table)
{
echo "<h2>" . $table[0] . "</h2>";
$query = "DESCRIBE " . $table[0];
$result = $mysqli->query($query);
$columns = $result->fetch_all();
foreach($columns as $column)
{
echo $column[0] . "<br />";
}
}
$mysqli->close();
?>