php - 如何从 PHP 脚本生成表格格式的输出

标签 php mysql tabular

以下是包含列和值的示例:

+----------------------------------------------------------------+
| rate | conn/s | req/s | replies/s avg | errors | net io (KB/s) |
+----------------------------------------------------------------+
|  100 | 99.9   | 99.9  | 99.7          | 0      | 45.4          |
|  120 | 119.7  | 119.7 | 120.0         | 0      | 54.4          |
|  140 | 139.3  | 139.3 | 138.0         | 0      | 63.6          |
|> 160 | 151.9  | 151.9 | 147.0         | 0      | 69.3          |
|  180 | 132.2  | 129.8 | 137.4         | 27     | 59.6          |
|  200 | 119.8  | 117.6 | 139.9         | 31     | 53.9          |
+----------------------------------------------------------------+

最佳答案

假设你想在浏览器中显示并从MySQL中获取数据。使用此代码,将您的 dbnametablename 替换为正确的值:

<html>
<head><title>Result as Table</title></head>
<body>
<?php
$db_host = 'localhost';
$db_user = 'root';
$db_pwd = '';

$database = 'dbname';
$table = 'tablename';

if (!mysql_connect($db_host, $db_user, $db_pwd))
    die("Can't connect to database");

if (!mysql_select_db($database))
    die("Can't select database");

// sending query
$result = mysql_query("SELECT * FROM {$table}");
if (!$result) {
    die("Query to show fields from table failed");
}

$fields_num = mysql_num_fields($result);

echo "<h1>Table: {$table}</h1>";
echo "<table border='1'><tr>";
// printing table headers
for($i=0; $i<$fields_num; $i++)
{
    $field = mysql_fetch_field($result);
    echo "<td>{$field->name}</td>";
}
echo "</tr>\n";
// printing table rows
while($row = mysql_fetch_row($result))
{
    echo "<tr>";

    // $row is array... foreach( .. ) puts every element
    // of $row to $cell variable
    foreach($row as $cell)
        echo "<td>$cell</td>";

    echo "</tr>\n";
}
mysql_free_result($result);
?>
</body></html>

关于php - 如何从 PHP 脚本生成表格格式的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4295477/

相关文章:

python - 使用 ManyToManyField 时如何从数据库中适本地选择条目?

javascript - 如何在 php 上获取动态创建的文本框的输入并使用循环将它们存储在 MySQL 中?

javascript - 单击标题可对表格进行排序

php - 从 3 个不同的表中获取最近的帖子,在 codeigniter 中将结果限制为 5 个

javascript - 如何将带有所需位置标记的 map 存储在文件中?

php - 如何使用图形 API 从 Facebook 页面获取最受欢迎的帖子

c++ - 在表格中格式化输出,C++

php - Zend Framework 值得吗?

MYsql经常无缘无故关机,重启后无法重启

LaTeX 表格太宽。如何使它合身?