如何实现 mysqli 输出表结构和字段

流程图

flowchart TD
    A(连接数据库) --> B(查询表结构和字段)
    B --> C(输出结果)

步骤表格

步骤 操作
1 连接到数据库
2 查询表结构和字段
3 输出查询结果

具体步骤和代码示例

步骤1:连接到数据库

```php
<?php
// 数据库信息
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDB";

// 创建连接
$conn = new mysqli($servername, $username, $password, $dbname);

// 检测连接
if ($conn->connect_error) {
    die("连接失败: " . $conn->connect_error);
}
?>

#### 步骤2:查询表结构和字段

```markdown
```php
<?php
// 查询表结构和字段
$sql = "SHOW TABLES";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $tableName = $row["Tables_in_myDB"];
        echo "表名: " . $tableName . "<br>";

        // 查询字段
        $sqlFields = "SHOW COLUMNS FROM " . $tableName;
        $resultFields = $conn->query($sqlFields);

        if ($resultFields->num_rows > 0) {
            while($rowFields = $resultFields->fetch_assoc()) {
                echo "字段: " . $rowFields["Field"] . "<br>";
            }
        }
    }
} else {
    echo "0 结果";
}
?>

#### 步骤3:输出查询结果

```markdown
```php
<?php
// 输出查询结果
echo "查询成功";

// 关闭连接
$conn->close();
?>

### 总结

通过以上步骤,我们可以连接到数据库,查询表结构和字段,并输出查询结果。希望这篇文章对你有所帮助,如果有任何问题,请随时向我提问。

### 作者

该文由经验丰富的开发者编写,如有疑问可随时联系。