我可以在MySQL数据库中显示所有表格和数据吗?

时间:2011-08-10 03:09:52

标签: php mysql database

我想将MySQL数据库中的所有表以及每个表中的所有记录作为单个网页输出。我可以使用SELECT函数为一个表执行此操作,但希望对快速更改的数据库执行此操作。随着时间的推移,将添加和删除新表,因此我想要一个通用函数,它将显示数据库中所有表的所有数据。这可能吗?

4 个答案:

答案 0 :(得分:1)

这将列出数据库中的所有表,并按表名和序号位置对它们进行排序。我省略了一些您可能不需要的列,但请仔细检查列选择。

好的......你得到的东西比平时给出的要多,但试试这个,看看它是不是你要找的东西。

<?php
$sql = "SELECT `TABLE_SCHEMA`,`TABLE_NAME`, `COLUMN_NAME`, `ORDINAL_POSITION`,
            `COLUMN_DEFAULT`, `IS_NULLABLE`, `DATA_TYPE`, `CHARACTER_MAXIMUM_LENGTH`,
            `CHARACTER_SET_NAME`, `COLLATION_NAME`, `COLUMN_TYPE`, `COLUMN_KEY`
        FROM INFORMATION_SCHEMA.COLUMNS
        ORDER BY `TABLE_SCHEMA`,`TABLE_NAME`,`ORDINAL_POSITION` ASC;";

mysql_connect($host, $username, $password) or die();
mysql_select_db($database) or die();
$result = mysql_query($sql);

$table_top = "<table cellpadding=\"2\" border=\"1\"><tr><th>Schema</th><th>Table</th><th>Column</th><th>Position</th><th>Key</th><th>Type</th><th>Max Length</th></tr>";
$table_change_row = "<tr><th bgcolor=\"black\"></th><th>Table</th><th>Column</th><th>Position</th><th>Key</th><th>Type</th><th>Max Length</th></tr>";
$table_bottom = "</table>";

$current_schema = '';
$current_table = '';

echo $table_top;

while ($row = mysql_fetch_object($result)) {
    if ($current_schema!=$row->TABLE_SCHEMA && !empty($current_schema))
    {
            echo $table_bottom;
            echo $table_top;
    }

    if ($current_table!=$row->TABLE_NAME)
    {
            echo $table_change_row;
    }

    $current_schema = $row->TABLE_SCHEMA;
    $current_table = $row->TABLE_NAME;
    echo "
    <tr>
            <td>$row->TABLE_SCHEMA</td>
            <td>$row->TABLE_NAME</td>
            <td>$row->COLUMN_NAME</td>
            <td>$row->ORDINAL_POSITION</td>
            <td>$row->COLUMN_KEY</td>
            <td>$row->DATA_TYPE</td>
            <td>$row->CHARACTER_MAXIMUM_LENGTH</td>
    </tr>";
}

echo $table_bottom;
?>

答案 1 :(得分:0)

使用此查询获取所选数据库中的所有表名

SELECT * FROM INFORMATION_SCHEMA.COLUMNS

使用 foreach 循环使用第二个循环来获取结构细节

DESCRIBE ;

or 
SELECT column_name,column_type,is_nullable,column_key,col  umn_default,extra FROM information_schema.COLUMNS WHERE 
table_name=''

通过使用php的组合,您可以获得所需的所有信息

答案 2 :(得分:0)

另一种方法,以更加词汇的方式列出事物。就个人而言,我会将所有内容转储到一个数组中并对其进行迭代,但我知道有些人更喜欢将其写入内联。

$dbName = 'foo';

$res = $mysqliCnx->query('show tables');
if ($res)
{
    while ($row = mysqli_fetch_assoc($res))
    {
        $currTable = $row['Tables_in_'.$dbName];
        echo '<h2>'.$currTable.'</h2><ul>';
        $res2 = $mysqliCnx->query('show columns from '.$currTable);
        while ($fields = mysqli_fetch_assoc($res2))
        {
             echo '<li>'.$row['field'].' - ('.$row['Type'].')</li>';
        }
        echo '</ul>';
    }
}

答案 3 :(得分:0)

function db_show_tables() {
  $o=mysql_query("show tables");
  if($o!==false) {
    while($w=mysql_fetch_row($o)) $lista[]=$w[0];
    return $lista;
  };
  return $o;
};
相关问题