我看过Google,但我找不到通过PHP显示SQL表的最佳,最简单的方法。我是PHP和SQL的新手,所以我有点困惑。到目前为止我有这个,但我甚至不确定行如何工作。我只是想显示整个表格。
<?php
$dbname = 'my_db';
if (!mysql_connect('localhost', 'username', 'password')) {
echo 'Could not connect to mysql';
exit;
}
$sql = "SHOW TABLES FROM $dbname";
$result = mysql_query($sql);
if (!$result) {
echo "DB Error, could not list tables\n";
echo 'MySQL Error: ' . mysql_error();
exit;
}
while ($row = mysql_fetch_row($result)) {
echo "Table: {*}\n";
}
mysql_free_result($result);
?>
答案 0 :(得分:0)
以下代码只应显示指定数据库中的表名。
while ($row = mysql_fetch_row($result)) {
echo "Table: {$row[0]}\n";
}
如果您想查看每个表的内容,您必须执行以下操作:
mysql_select_db($dbname);
while ($row = mysql_fetch_row($result)) {
//echo "Table: {$row[0]}\n";
$query = "SELECT * FROM $row[0]";
$table = mysql_query($query);
echo "<table>";
while($content = mysql_fetch_array($table)){
echo "<tr>";
foreach($content as $key => $value){
echo "<td>" . $value . "</td>";
}
echo "</tr>";
}
echo "</table>";
}
答案 1 :(得分:0)
您所寻找的可能是DESCRIBE
http://dev.mysql.com/doc/refman/5.0/en
/describe.html会给你一些类似的东西:
mysql> DESCRIBE City;
+------------+----------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+----------+------+-----+---------+----------------+
| Id | int(11) | NO | PRI | NULL | auto_increment |
| Name | char(35) | NO | | | |
| Country | char(3) | NO | UNI | | |
| District | char(20) | YES | MUL | | |
| Population | int(11) | NO | | 0 | |
+------------+----------+------+-----+---------+----------------+
如果您替换代码的这一部分
while ($row = mysql_fetch_row($result)) {
echo "Table: {*}\n";
}
通过
while ($row = mysql_fetch_row($result)) {
print_r($row);
}
您将更好地理解$row
设置的内容。
<强>更新强>
另一方面,如果您只是想获取某些表中的所有数据,那么您需要执行的查询是SELECT
http://dev.mysql.com/doc/refman/5.0/en/select.html,它将是这样的:< / p>
$sql = "SELECT * FROM table_name";