简体   繁体   中英

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.

Here is how my mysql table looks:

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;

<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.

In that case total_dates is 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). 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 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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