1

I have a challenge I am trying to add all the time the user has spent online but I am getting wrong totals. I am taking values from mysql database and I want to get total hours, minutes and seconds for each user. Currently I am getting totals for each session but now I want total for all sessions and display all users in a table where I have username and time spent online and must be able to filter results by date getting total time spent in hours, minutes and seconds for the filtered date. How can I do that. My code is as follows:

 $i=0;
    foreach ($report as $online) 
    {
    $id = $online['userid'];

    $sql = "SELECT start_time, end_time FROM user_sessions where userid=$id AND end_time !='0000-00-00' || end_time != '' LIMIT $start, $per_page";

    $timeOnline = $obj->MySQLSelect($sql);
    ++$i;
    $start = $timeOnline[$i]['start_time'];
    $end = $timeOnline[$i]['end_time'];
    $totalhours = get_saved_time($end, $dstart);                                                      
    $sum = $totalhours;
    ?>
    <tr class="gradeA">
    <?php if (!empty($sum)): ?>
     <td><? echo $generalobjAdmin->clearName($online['fname'].' '.$online['lname']); ?></td>
     <td align="center"><?= Convert($sum); ?></td>
    <?php endif; ?>
    </tr>
    <?  } ?>

    public function get_saved_time($end_time,$start_time)
     {
      $past = $start_time;
      $current = strtotime($end_time); 
      $past = strtotime($past);
      return round(abs($current-$past));            
      }
function Convert($seconds) {

$hours = floor($seconds / 3600);

$mins = floor(($seconds / 60) % 60);

$secs = $seconds % 60;



if (strlen($hours) == 1)

$hours = "0" . $hours;

if (strlen($secs) == 1)

$seconds = "0" . $secs;

if (strlen($mins) == 1)

$minutes = "0" . $mins;



if ($hours == 0){

    $mint="";

    $secondss="";

    if($mins > 01){

        $mint = "$mins mins";

    }else{

        $mint = "$mins min";

    }

    if($secs > 01){

        $secondss = "$secs seconds";

    }else{

        $secondss = "$secs second";

    }

     $ret = "$mint $secondss";

} else {

    $mint="";

    $secondss="";

    if($mins > 01){

        $mint = "$mins mins";

    }else{

        $mint = "$mins min";

    }

    if($secs > 01){

        $secondss = "$secs seconds";

    }else{

        $secondss = "$secs second";

    }

    if($hours > 01){

      $ret = "$hours hrs $mint $secondss";

    }else{

      $ret = "$hours hr $mint $secondss";

    }

}

return $ret;
}
Ngoni
  • 49
  • 1
  • 4
  • do it in SQL, with DATEDIFF() and TIME DIFF() https://stackoverflow.com/questions/3528219/mysql-how-to-get-the-difference-between-two-timestamps-in-seconds – michal Oct 10 '18 at 16:22

0 Answers0