1

I'm working on a time management system and am currently stuck. I'm trying to use PHP to calculate the number of hours/minutes between two columns (from and to). These are both set as 'time' type so MySQL recognises it as a time datatype.

I've tried the following in PHP:

$from= isset($_GET['from']) ? '%'.$_GET['from'].'%' : '';    
$to = isset($_GET['to']) ? '%'.$_GET['to'].'%' : '';    
$diff = $to - $from;    


echo "<table border='1'>    
echo "<tr>";    
echo "<td>" . $row[$diff] . "</td>";    
echo "</tr>";    
echo "</table>"; 

Say for example 'to' is set at 15:00:00 and from is set at 09:00:00, then the time difference for that row should be 6 hours and this should be displayed for that row.

The variable $difference is supposed to echo the difference in hours/minutes but it just displays the id assigned to that row instead. I'm trying to echo the number of minutes for each row in the table not just one.

I've seen the timediff function but don't know if that will do the trick.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
  • Why are you taking the values from $_GET parameters? You probably want to calculate the difference directly in the database server: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_timediff – Pavel S. Feb 22 '14 at 15:09

1 Answers1

0

I don't see your logic with the % and the $_GET vars, and $row suddenly appears out of nowhere. You should convert the inputted times to php DateTime classes. An example shows calculating diffs: http://nl1.php.net/manual/en/class.datetime.php#108970 Create your DateTime for example like this: $dateFrom = new DateTime("2014-02-24 ".$_GET['from']); $dateTo = new DateTime("2014-02-24 ".$_GET['to']); $diff = $dateFrom->diff($dateTo); print_r($diff) ; The day you use is not really important if you only need the difference in time.

Mallesbixie
  • 180
  • 1
  • 7
  • I was more after something like this [http://stackoverflow.com/questions/365191/how-to-get-time-difference-in-minutes-in-php] but didn't want to be using `strtotime` as I want to declare the column names 'from' and 'to' instead so it loops through all the rows in the table with the last column showing the number of hours/minutes between 'from' and 'to' – user3340885 Feb 23 '14 at 09:49
  • Having used you code, it displays an error for the 'from' and 'to' fields as being an undefined index _Notice: Undefined index: ...on line 120 Notice: Undefined index: to...on line 121 DateInterval Object ( [y] => 0 [m] => 0 [d] => 0 [h] => 0 [i] => 0 [s] => 0 [invert] => 0 [days] => 0 )_ – user3340885 Feb 23 '14 at 09:51