coffee_cn

博客园 首页 新随笔 联系 订阅 管理
<?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;    
}
?>

 

posted on 2013-01-07 11:30  coffee  阅读(1351)  评论(0编辑  收藏  举报