donglan8999 2013-10-03 08:55
浏览 56
已采纳

来自SQL查询的每个日期的HTML表

I need to output the result from an SQL query as a table for each date. Each date has several rows with a uniqe id, a system name and a remark.

mysql_connect("$host", "$username", "$password")or die("cannot connect"); 
mysql_select_db("$dbname") or die("cannot select DB");


    $query = " 
    SELECT id, Date, System, Remark FROM records WHERE Date BETWEEN '$from' AND '$to'
    ORDER BY Date, CASE System 
        WHEN 'System1' THEN 1
        WHEN 'System2' THEN 2
        WHEN 'System4' THEN 3
        WHEN 'System5' THEN 4
        ELSE 19
        END
    ";

$result = mysql_query($query);

How do I proceed from this to generate a table that contains all rows with the same date:

<table>
<tr><th colspan="3"> Display date here</th></tr>
<tr>
    <td>Display System here</td>
    <td>Display Remark here</td>
    <td>Display id here</td>
</tr>
    <tr>
    <td>Display System here</td>
    <td>Display Remark here</td>
    <td>Display id here</td>
</tr>
    <tr>
    <td>Display System here</td>
    <td>Display Remark here</td>
    <td>Display id here</td>
</tr>
</table>
  • 写回答

2条回答 默认 最新

  • dongzhong5756 2013-10-03 09:41
    关注

    Try this

    <php
    $previous_date="";
    
    echo "<table>";
    while ($row=mysql_fetch_array($result))
    {
    $new_date=$row["date"];
    if ($previous_date!=$new_date && $previous_date!="")
    echo "</table><table>";
    
    if ($previous_date!=$new_date)
    echo "<tr><th colspan='3'>".$row["date"]."</th></tr>";
    
    echo "<tr>";
    echo "<td>".$row["system"]."</td>";
    echo "<td>".$row["remark"]."</td>";
    echo "<td>".$row["id"]."</td>";
    echo "</tr>";
    
    $previous_date=$new_date;
    }
    echo "</table>";
    ?>
    

    Edited

    Adding explanation:

    For each loop i check if this is a new date. If yes, then i close previous table, i create a new one and i echo the table header.

    I had to handle the case of the first table to be opened (this is the case when $previous_date is empty). Then i just insert the header.

    The first table is opened before the while loop, and the last table closes after the while loop.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大