首页 > 解决方案 > 使用foreach在html表中回显mysql数据

问题描述

我正在根据日期从数据库中检索记录,并希望根据日期显示所有记录。例如,星期一的记录应该低于星期一的标题,而星期二的记录应该低于星期二的标题。就我而言,有时星期一的一些记录在星期三以下可见。我如何实现这一目标?

<th>Monday</th>
<th>Tuesday</th>
<th>Wednesday</th>

<?php foreach($result as $r){
?>
<tr>
<?=$r->colname?>
</tr>

<?php }?>

标签: phpsortingdatedatetime

解决方案


你可以这样做:

$query="SELECT * FROM table WHERE stuff = "otherstuff"";    
$res=$conn->query($query);
     while($row=$res->fetch_assoc()){

        echo "<table>";
        echo "<tr><th>".$row['date']."</th></tr>"; //here you get each date filtered by rows
        echo "<tr>";
        echo "<td>".$row['stuff']."</td>"; //data1
        echo "</tr>";
        echo "<tr>";
        echo "<td>".$row['otherstuff']."</td>"; //data2
        echo "</tr>";
        echo "</table>";
}

在 html5 表中打印 myslq 查询的内容时,我建议使用 while() 而不是 foreach()。它遍历 while() 并为每一行生成一个表。

您的表格应如下所示:

Date    Stuff  Otherstuff  Morestuff
Monday  data1  data2       data3        //this one gets an own table
Tuesday XY     XY          XY           //this one gets the next table

推荐阅读