简体   繁体   English

在html表中显示来自mysql的数据

[英]Display data from mysql in html tables

I can't figure out how to display data from mysql in separate html tables within one loop. 我不知道如何在一个循环内在单独的html表中显示来自mysql的数据。

Here is how my mysql table looks: 这是我的mysql表的外观:

date         name
----         ----
2011-02-02   Katrin
2011-02-02   Michael
2011-02-02   Joe
2011-02-05   David
2011-02-05   Steve
etc...

NOTE: I know how to get data from the table. 注意:我知道如何从表中获取数据。

The idea is to create individual table based on date. 这个想法是基于日期创建单个表。 For example here is html that should be generated; 例如,这里是应生成的html。

<table>
<tr>
   <td>date</td><td>name</td>
   <td>2011-02-02</td><td>Katrin</td>
   <td>2011-02-02</td><td>Michael</td>
   etc..
</tr>
</table>

<table>
<tr>
   <td>date</td><td>name</td>
   <td>2011-02-05</td><td>Joe</td>
   <td>2011-02-02</td><td>David</td>
   etc..
</tr>
</table>

Here is what I try. 这是我尝试的。

I have counted how many distinct dates are fetched from table. 我已经计算了从表中获取了多少个不同的日期。 After that I use "for" statement to "draw" the tables. 之后,我使用“ for”语句“绘制”表。

In that case total_dates is 2 在这种情况下total_dates是2

<?php for($x = 0; $x < $total_dates; $x++): ?>
<table>
  <tr>

  <tr>
</table>
<?php endif; ?>

So far so good. 到现在为止还挺好。 That code draw the tables. 该代码绘制表格。 The problem is that I can't figure out programic logic how to display data within tables so every table to contain data grouped by date. 问题是我无法弄清楚程序逻辑如何在表中显示数据,因此每个表都包含按日期分组的数据。

You might want to group your data based on the date first (look at the GROUP BY statement). 您可能希望首先根据日期对数据进行分组(请查看GROUP BY语句)。 If you have that in order, you can just loop through the data record by record. 如果您有此顺序,则可以逐条记录遍历数据记录。 Include an if-statement in each iteration that check whether the date is changes compared to the previous iteration. 在每个迭代中都包含一个if语句,以检查该日期与前一次迭代相比是否发生了变化。 If that is the case, close the table and open a new one. 如果是这种情况,请关闭表格并打开一个新表格。 Like (not tested): 喜欢(未经测试):

<table>
<? $prevDate = null; ?>
<? foreach($myData as $row){ ?>
  <? if($prevDate != null && $prevDate != $row['date']) { ?>
     </table><table>
  <? } ?>

  <tr>    
    <td>date</td>
    <td>name</td>    
    <td>2011-02-02</td>
    <td>Katrin</td>    
    <td>2011-02-02</td>
    <td>Michael</td>
  </tr>

<? $prevDate = $row['date']; ?>
<? } ?>

You can do it in one loop but the condition is that you need the date to be ordered. 您可以在一个循环中完成此操作,但条件是您需要订购日期。

Just do something like this : 只是做这样的事情:

$table_header = '<table><tr><th>Header 1</th><th>Header 2</th></tr>';
$table_end = '</table>';

$flag = false;
echo $table_header;
for ($x in $total) {
    if ($flag != $x->date && $flag != false) {
        echo $table_end;
        echo $table_header;
    }
    // Display table content for the current row
    echo '<tr><td>'.$value.'</td><td>'.$value.'</td></tr>';
    $flag = $x->date;
}
echo $table_end;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM