zoukankan      html  css  js  c++  java
  • 利用PHP生成MySQL数据库表结构信息

    <?php
    $db = 'ecs_e94f4d07d259f246';
    $conn = open_db($db);
    $data = show_db($db);
    echo($data);
    
    // 获取数据库信息
    function show_db($db) {
        $data = '<h1>数据库设计说明书('.$db.')</h1>';
        $tables = show_tables();
        foreach($tables as $key=>$val) {
            $table = current($val);
            $data .= '<table border="1" cellspacing="0">';
            $data .= '<caption><h2>' . $table . '</h2></caption>';
            $data .= '<tr bgcolor="#cccccc"><th width="130">Field</th><th width="200">Desc</th><th width="180">Type</th><th width="80">Null</th><th width="80">Key</th><th width="80">Default</th><th width="120">Extra</th></tr>';
            $fields = describe($table);
            foreach($fields as $item) {
                $data .= '<tr><td>'.$item['Field'].'</td><td>&nbsp</td><td>'.$item['Type'].'</td><td>'.$item['Null'].'</td><td>'.($item['Key'] ? $item['Key'] : '&nbsp').'</td><td>'.($item['Default'] ? $item['Default'] : '&nbsp').'</td><td>'.($item['Extra'] ? $item['Extra'] : '&nbsp').'</td></tr>';
            }
            $data .= '</table>';
            $data .= '<br/>';
        }
        $data .= '';
        return $data;
    }
    
    // 连接数据库
    function open_db($db) {
        $conn = mysql_connect('127.0.0.1', 'root', 'mysql');
        if (!$conn) {
            die('Could not connect: ' . mysql_error());
        }
        if (!mysql_select_db($db, $conn)) {
            die ('Can\'t use ' . $db . ' : ' . mysql_error());
        }
        return $conn;
    }
    
    // 关闭数据库连接
    function close_db($con) {
        mysql_close($con);
    }
    
    // 获取全部数据表
    function show_tables() {
        $sql = "SHOW TABLES";
        return query($sql);
    }
    
    // 获取数据表结构信息
    function describe($table) {
        $sql = "DESCRIBE $table";
        return query($sql);
    }
    
    // 执行SQL
    function query($sql) {
        $res = mysql_query($sql, $GLOBALS['conn']);
        if(!$res) {
            die('Invalid query: ' . mysql_error());
        }
        $list = array();
        while ($row = mysql_fetch_assoc($res)) {
            $list[] = $row;
        }
        return $list;    
    }
    ?>
  • 相关阅读:
    四则运算3.2
    第二周进度条
    构建之法阅读笔记02
    四则运算2
    第一周进度条
    构建之法阅读笔记01
    四则运算 Python
    第一周第二周学习进度条
    《构建之法》学习中疑问
    小学四则运算1.0
  • 原文地址:https://www.cnblogs.com/coffee_cn/p/2848929.html
Copyright © 2011-2022 走看看