您的位置:首页 > 编程语言 > PHP开发

利用PHP生成MySQL数据库表结构信息

2013-01-07 11:30 531 查看
<?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> </td><td>'.$item['Type'].'</td><td>'.$item['Null'].'</td><td>'.($item['Key'] ? $item['Key'] : ' ').'</td><td>'.($item['Default'] ? $item['Default'] : ' ').'</td><td>'.($item['Extra'] ? $item['Extra'] : ' ').'</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;
}
?>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: