3

I'm echoing my MYSQL database using PHP and trying to calculate the difference of "time" in each row for the column "time". I have "time" stored in TIME format HH:MM:SS (00:00:00) in the MYSQL database. Example of the output I'm trying to achieve:

Saved On | Time (MM:SS) | + / - Time (MM:SS)
----------------------------------
TIMEDATE | 00:11       | + 00:05 |
----------------------------------
TIMEDATE | 00:06       |  00:00  |
----------------------------------
TIMEDATE | 00:06       | - 1:00  |
----------------------------------
TIMEDATE | 00:07       |  00:00  |
----------------------------------

My current mysql query + php:

$result = mysql_query("SELECT * FROM timer WHERE user_id = '$userid' ORDER BY savedon DESC") 
or die(mysql_error());  

echo "<table class='sortable'>";
echo "<tr> <th>Saved On</th> <th>Time (MM:SS)</th> <th>+/-</th> </tr>";
    while($row = mysql_fetch_array( $result )) {
echo "<tr><td>";
echo $row['savedon'];
echo "</td><td>"; 
echo $row['time'];
echo "</td><td>"; 
echo $row['time']; // My issue is right here. I have no clue on how to calculate the +/- difference of times
echo "</td></tr>";  

}

echo "</table>";

My issues:

  1. I'm trying to format the time to drop the hour prefix. Example: 00:06 (MM:SS) instead of 00:00:06 (HH:MM:SS).

  2. Each row should calculate the difference of times as demonstrated above.

I'm not sure if this should be handled with MYSQL in the query or with PHP. Any help would be appreciated.

Adrian Cid Almaguer
  • 7,815
  • 13
  • 41
  • 63
michelle
  • 623
  • 2
  • 6
  • 22

2 Answers2

1

I think that is better make this in PHP

Make a loop and inside you can use something like this:

$one = new DateTime($firstDate);
$two = new DateTime($secondDate);
$interval = $two->diff($one);

echo $interval->format('%I:%S');

http://php.net/manual/en/dateinterval.format.php

Adrian Cid Almaguer
  • 7,815
  • 13
  • 41
  • 63
0

Can use subselect if need time difference between [id] and [id before id].

SELECT TIMEDIFF(t1.time_row, (
    SELECT time_row FROM tablename t2 WHERE t2.id < t1.id ORDER BY id DESC LIMIT 1)
  )
FROM tablename t1
Ondřej Machala
  • 133
  • 1
  • 6