SQL到PHP数组中,便于创建表

时间:2014-08-02 13:47:15

标签: php html sql arrays html-table

我的数据库架构是

CREATE TABLE "tests" (
"id" integer UNIQUE,
"type" integer NULL,
"monitor" integer NULL,
"name" varchar(255) NULL,
PRIMARY KEY (id, name)
);

CREATE TABLE "summary" (
"id" integer PRIMARY KEY AUTOINCREMENT,
"testid" integer NULL,
"timestamp" datetime NULL,
"total" integer NULL,
);

我的SQL查询是:

SELECT "s"."testid", AVG(total) AS "total" , DATE(timestamp) AS "d"
FROM "summary" AS "s"
INNER JOIN "tests" AS "t" ON s.testid = t.id
WHERE (timestamp >= date('now', '-7 days'))
GROUP BY "d", "testid" ORDER BY "d" DESC

返回以下数据示例数据:

Test A | 2014-07-30 | 100
Test B | 2014-07-30 | 99
Test C | 2014-07-30 | 98
Test A | 2014-07-31 | 100
Test B | 2014-07-31 | 99
Test C | 2014-07-31 | 98
Test A | 2014-08-01 | 100
Test B | 2014-08-01 | 99
Test C | 2014-08-01 | 98

我希望的最终目标是拥有一个显示上述数据的HTML表格:

Test Name | 2014-07-30 | 2014-07-31 | 2014-08-01
------------------------------------------------  
Test A         100          100          100
Test B          99           99           99
Test C          98           98           98

我正在努力从SQL创建所需的PHP数组,然后循环并创建表。

任何帮助都会非常感激!

1 个答案:

答案 0 :(得分:2)

由于您没有编写任何代码,因此我很难帮助您。

基本理念是:

$query = mysql_query("SELECT * FROM your_table");
echo "<table>";
while($row = mysql_fetch_assoc($query))
{

echo "<tr><td>$row['your_cell_name']</td></tr>";

}
echo "</table>";

当您上传代码时,我将能够为您提供更多帮助。

我假设您将phpmysql服务器一起使用。

修改

我要做的是:

  1. 在测试名称列中找到不同的项目
  2. 找到不同的日期
  3. 使用基本SQL WHERE在2014-07-30找到测试A并将其回显到<td>标记
  4. 示例:

    $query = mysql_query("SELECT DISTINCT timestamp FROM summary");
    echo "<table><tr><td>Test Name</td>"
    while($row = mysql_fetch_array($query))
    {
        foreach($row as $date)
        {
            echo "<td>{$date}</td>"
        }
    }
    echo "</tr><tr>";
    $query = mysql_query("SELECT DISTINCT testid FROM summary");
    while($row = mysql_fetch_array($query))
    {
        foreach($row as $testid){
            echo "<td>{$testid}</td>";
            $sum_query = "YOUR QUERY FOR THE SCORE OF THE TEST";//you can use $testid to find all of the summery at the distinct date
            //Hope you understand what I did
        }
    }
    echo "</tr>";