Last active
August 29, 2015 14:24
-
-
Save Moln/153e991b3cc17bdd6afe to your computer and use it in GitHub Desktop.
数据表结构, 导出 markdown 格式
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| $dsn = 'mysql:dbname=test;host=192.168.66.49'; | |
| $user = 'root'; | |
| $password = ''; | |
| try { | |
| $dbh = new PDO($dsn, $user, $password); | |
| } catch (PDOException $e) { | |
| echo 'Connection failed: ' . $e->getMessage(); | |
| } | |
| $tables = $dbh->query('select `TABLE_NAME`,`TABLE_COMMENT` from `information_schema`.`TABLES` where `TABLE_SCHEMA`=(SELECT DATABASE())', \PDO::FETCH_ASSOC)->fetchAll(); | |
| foreach ($tables as $table) { | |
| echo sprintf("## %s `%s`\n\n", $table['TABLE_COMMENT'], $table['TABLE_NAME']); | |
| $sql = sprintf('show full columns from `%s`', $table['TABLE_NAME']); | |
| $columns = $dbh->query($sql, PDO::FETCH_ASSOC)->fetchAll(); | |
| $colMaxLen = []; | |
| foreach ($columns as $col) { | |
| foreach ($col as $key => $val) { | |
| if (!isset($colMaxLen[$key])) { | |
| $colMaxLen[$key] = strlen($key); | |
| } | |
| if ($key == 'Comment') { | |
| $val = iconv('utf-8', 'gbk', $val); | |
| } | |
| if ($colMaxLen[$key] < strlen($val)) { | |
| $colMaxLen[$key] = strlen($val); | |
| } | |
| } | |
| } | |
| $title = false; | |
| foreach ($columns as $col) { | |
| unset ($col['Privileges'], $col['Collation']); | |
| $col['Comment'] = iconv('utf-8', 'gbk', $col['Comment']); | |
| $row = []; $line = []; | |
| foreach ($col as $key => $val) { | |
| $row[str_pad($key, $colMaxLen[$key])] = str_pad($val, $colMaxLen[$key]); | |
| $line[] = str_pad('', $colMaxLen[$key], '-'); | |
| } | |
| if (!$title) { | |
| echo '| ', implode(" | ", array_keys($row)), " |\n"; | |
| echo '| ', implode(" | ", $line), " |\n"; | |
| $title = true; | |
| } | |
| echo '| ', implode(" | ", $row), " |\n"; | |
| } | |
| echo "\n\n"; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment