DiegoP.
DiegoP.

Reputation: 45757

Doing a calculation in a while loop

I have the following variables inside a WHILE loop:

    $row['To'];
    $row['From'];

Those represent a time, example:

$row['To'] ="10:00:00";
 $row['From'] = "08:00:00";

In a normal calculation I will do the following to get the hours in difference:

 $result = (strtotime($row['To']) - strtotime($row['From']));
   $hours      = floor($result / 60 / 60);
   $minutes    = round(($result - ($hours * 60 * 60)) / 60);

The problem is that now I have to do in a while loop, where $row['to'] and $row['From'] must be calculated all the times the loop dictate...But I cannot get it work. This is what I tried:

function calculateHours($project, $worker, $year, $month) {
if($project) {
$q='SELECT * FROM project_timeline WHERE ID="'.$project.'" AND Year(Date) = "'.$year.'" AND Month(Date) = "'.$month.'" AND WorkerID="'.$worker.'"';
 }else{
$q='SELECT * FROM project_timeline WHERE Year(Date) = "'.$year.'" AND Month(Date) = "'.$month.'" AND WorkerID="'.$worker.'"';
 }
 $r=mysql_query($q) or die(mysql_error());   
   while($row = mysql_fetch_array($r)) {
    $result .= (strtotime($row['To']) - strtotime($row['From']));
   }
    $hours      = floor($result / 60 / 60);
    $minutes    = round(($result - ($hours * 60 * 60)) / 60);
 return $hours.' hour(s) and '.$minutes.' minutes';
}

How can I fix it? Thanks

Upvotes: 1

Views: 1065

Answers (3)

FtDRbwLXw6
FtDRbwLXw6

Reputation: 28929

I would use the DateTime class for this:

// other function code here...

$from = new DateTime($row['From']);
$to   = new DateTime($row['To']);
$diff = $from->diff($to);

return $diff->format('%h hour(s) and %i minutes');

Upvotes: 0

Marc B
Marc B

Reputation: 360912

Using return like that inside your while() loop is going to terminate the loop on the first iteration and only ever produce results for the FIRST row of data you've fetched from the database.

Upvotes: 0

SergeS
SergeS

Reputation: 11799

Why are you using .= for calculating numbers ( time ) in PHP this is string addition , for adding numbers use +=.

And just for clever code - put $result = 0; in the beginning of the function

PS. Also instead of floor, try to use % -

$result     = round($result / 60);
$minutes    = $result % 60;
$hours      = ( $result - $minutes ) / 60;

Upvotes: 1

Related Questions