Search code examples
phpmysqltimehtml-tableseparator

Insert empty row in table to separate times each 30 minutes in PHP MySQL


I'm showing certain information stored in a MySQL table in an HTML table. One of the columns of the table is of type "time". My idea is that the rows are spaced in groups of 30 minutes. The way it should be is as follows:

08:00
08:15
08:25
----separator
08:35
08:55
----separator
09:00
09:15

I managed to do something, but it does not work very well.

Here's what I've done:

<?$lastTime = '';?>
<?while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) { ?>
<?$currentMinutes = substr($row["time"],3,2);?>
<?$lastMinutes = substr($lastTime,3,2);?>
<?if ( $lastTime <> '' and ($currentMinutes <> $lastMinutes) and ( ($lastMinutes <> '00' or $lastMinutes <> '30') and ($currentMinutes == '00' or $currentMinutes == '30' )  ) ){?>
<tr><td>Separator</td></tr>
<?}?>
<tr><td><?=$row["time"];?></td></tr>
<?$lastTime = $row["time"];?>
<?}?>

It is convenient to do this, or is there any way to solve it in the MySQL query?


Solution

  • If you could update your query to capture the intervals with

    select `time`, subtime(`time`,maketime(0,mod(minute(`time`),30),0)) as period
    from table;
    
    time        period
    08:00:00    08:00:00
    08:15:00    08:00:00
    08:25:00    08:00:00
    08:35:00    08:30:00
    08:55:00    08:30:00
    09:00:00    09:00:00
    09:15:00    09:00:00
    

    You could have PHP code that outputs the separator whenever period changes from the previous value.

    $period = '';
    while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
      if ($row['period'] != $period) {
        // Output separator
      }
      $period = $row['period'];
    }
    

    If you wanted to skip the first separator, then you could check that $period != ''.