如何在不知道字段名的情况下加载整个数据库


How to load the entire database without knowing its field names?

是否可以在不知道字段名称的情况下通过php读取数据库?所以它会像:

1.获取表"myTable"的结果数组。

2.计算每行中有多少字段。

3.循环创建html表并回显该值。

通常我们知道表的字段名,所以很容易阅读。如果你不知道字段名称怎么办?

谢谢。

使用*瞄准所有字段:

select * from myTable

如果您有多个表,您可以在*前面加上表的名称:

select
    another_table.*
from
    my_table
    left join another_table on another_table.id = my_table.another_table_id;

或者,可以使用show fields in myTableshow full fields in myTable仅获取字段列表(无数据)。

<?php
//connection variables
$host = "";
$database = "";
$user = "";
$pass = "";
//connection to the database
mysql_connect($host, $user, $pass)
or die ('cannot connect to the database: ' . mysql_error());
//select the database
mysql_select_db($database)
or die ('cannot select database: ' . mysql_error());
//loop to show all the tables and fields
$loop = mysql_query("SHOW tables FROM $database")
or die ('cannot select tables');
while($row = mysql_fetch_array($loop))
{
echo "
<table cellpadding=2 cellspacing=2 border=0 width=75%>
<tr bgcolor=#666666>
<td colspan=5><center><b><font color=#FFFFFF>” . $row[0] . “</font></center></td>
</tr>
<tr>
<td>Field</td><td>Type</td><td>Key</td><td>Default</td><td>Extra</td>
</tr>";
$i = 0;
$loop2 = mysql_query("SHOW columns FROM " . $row[0])
or die ('cannot select table fields');
while ($row2 = mysql_fetch_array($loop2))
{
echo "<tr ";
if ($i % 2 == 0)
echo "bgcolor=#CCCCCC";
echo "><td>" . $row2[0] . "</td><td>" . $row2[1] . "</td><td>" . $row2[2] . "</td><td>" . $row2[3] . "</td><td>" . $row2[4] . "</td></tr>";
$i++;
}
echo "</table><br/><br/>";
}
?>

来源:http://jadendreamer.wordpress.com/2009/01/13/print-all-mysql-database-tables-fields-using-php/

这应该可以做到:

$res = mysql_query("SELECT * FROM MyTable");
$rows_count = mysql_num_rows($res);
echo '<table>';
for($i=0; $i<$rows_count; $i++)
{
    echo '<tr>';
    $row = mysql_fetch_row($res);
    for($r=0;$r<count($row);$r++)
    {
        echo '<td>';
        echo $row[$r];
        echo '</td>';   
    }
    echo '</tr>';
}
echo '</table>';

您可以:

SELECT `COLUMN_NAME`, `TABLE_NAME`
FROM information_schema.`COLUMNS`

这里有一个快速而肮脏的脚本,可以在不知道字段的情况下获取整个表数据:

<?php
$conn = mysql_connect('localhost', 'root', ''); 
$sql = "SELECT * FROM `mysql`.`tables_priv`";
$rs = mysql_query($sql);
$tableText = "<table></table>";
$tableHeader = array();
$tableContent = '';
$tableHeaderSet = false;
while( false !== ($r = mysql_fetch_assoc($rs)))
{
    if(false == $tableHeaderSet)
    {
        $tableHeaderText = "<tr>";
        foreach( $r as $key=>$val)
        {
            $tableHeader[$key] = $key;
            $tableHeaderText .= "<th>$key</th>";
        }
        $tableHeaderText .= "</tr>";
    }
    $tableHeaderSet = true;
    $tableContent .= "<tr>";
    foreach( $tableHeader as $fieldName)
    {
        $tableContent .= "<td>" . $r[ $fieldName ] . "</td>";
    }
    $tableContent .= "</tr>";
}
echo "<table>{$tableHeaderText}{$tableContent}</table>";
?>

您可以使用系统表。例如,在Oracle数据库中,表ALL_TAB_COLUMNS包含有关用户的表、视图和集群的列的信息。