[英]What is the best way to display a SQL table through PHP?
I've looked on Google, but I haven't been able to find the best, simplest way to display SQL tables through PHP. 我看过Google,但是我找不到能够通过PHP显示SQL表的最佳,最简单的方法。 I'm new at PHP and SQL, so I'm a bit confused.
我是PHP和SQL的新手,所以有点困惑。 I have this so far, but I'm not even sure how the rows work.
到目前为止,我已经知道了,但是我什至不确定行的工作方式。 I just want to display the whole table.
我只想显示整个表格。
<?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);
?>
The below code should only show you the table names in the specified database. 以下代码仅应向您显示指定数据库中的表名。
while ($row = mysql_fetch_row($result)) {
echo "Table: {$row[0]}\n";
}
If you want to view the content of each table you will have to do something like this: 如果要查看每个表的内容,则必须执行以下操作:
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>";
}
Probably what you're looking for is DESCRIBE
http://dev.mysql.com/doc/refman/5.0/en /describe.html which will give you something like: 您可能正在寻找的是
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 | |
+------------+----------+------+-----+---------+----------------+
If you replace this parte of your code 如果您替换代码的这一部分
while ($row = mysql_fetch_row($result)) {
echo "Table: {*}\n";
}
by 通过
while ($row = mysql_fetch_row($result)) {
print_r($row);
}
you will undestand better what $row
is set to. 您会更好地理解
$row
被设置为什么。
UPDATE 更新
On the other hand, if you're just trying to fetch all data you have in some table, the query you have to do is a SELECT
http://dev.mysql.com/doc/refman/5.0/en/select.html which will be something like this: 另一方面,如果您只是想获取某个表中的所有数据,则必须执行的查询是
SELECT
http://dev.mysql.com/doc/refman/5.0/en/select。 html将会是这样的:
$sql = "SELECT * FROM table_name";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.