数据库表结构利用php导出为markdown文件
<?php
function getMd($servername, $username, $password, $dbname)
{
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
$result = $conn->query("show tables");
if ($result->num_rows > 0) {
$mark = '#' . $dbname . '数据库' . PHP_EOL;
while ($row = $result->fetch_assoc()) {
$table_name = $row["Tables_in_{$dbname}"];
$obj = $conn->query("show full columns from {$table_name}");
$table_comment = $conn->query("SELECT TABLE_COMMENT FROM INFORMATION_SCHEMA.TABLES WHERE table_name = '{$table_name}'")->fetch_assoc();
$mark .= '###' . $table_name . ' ' . $table_comment['TABLE_COMMENT'] . PHP_EOL;
$mark .= '| 字段名 | 数据类型 | 备注 |' . PHP_EOL;
$mark .= '| ------ | ------ | ------ |' . PHP_EOL;
while ($data = $obj->fetch_assoc()) {
$mark .= '| ' . $data['Field'] . ' | ' . $data['Type'] . ' | ' . $data['Comment'] . ' | ' . PHP_EOL;
}
$sql = $conn->query("show create table {$table_name}")->fetch_assoc();
$mark .= '```sql' . PHP_EOL;
$mark .= $sql["Create Table"] . PHP_EOL;
$mark .= '```' . PHP_EOL;
}
file_put_contents('表结构说明.md', $mark, FILE_APPEND);
}
$conn->close();
}
$params = $_GET;
$servername = empty($params['host']) ? "localhost" : $params['host'];
$username = empty($params['user']) ? "root" : $params['user'];
$password = empty($params['password']) ? "root" : $params['password'];
$dbname = empty($params['dbname']) ? "ht_silo" : $params['dbname'];
getMd($servername, $username, $password, $dbname);