Search code examples
phpmysqlcodeignitercodeigniter-2codeigniter-3

How to get the sum of time in a column of all rows using mysql


I have a table which contains duration column that is of type time. I am using codeigniter and mysql i want that time to be summed up. So that i can display that in total seconds, hours or minutes.Please help to sort out this issue.

enter image description here

$condition = "itemid =" . "'" . $section_id . "'";
$this->db->select('*, SEC_TO_TIME(SUM(TIME_TO_SEC(`duration`))) AS timeSum ');
$this->db->from('duration');
$this->db->where($condition);
$query = $this->db->get();


foreach($query->result_array() as $row1)
{
$row['course_data'][] = $row1;
echo "time".$row1['timeSum']."<br/>";
}

Solution

  • Use SEC_TO_TIME to convert time into second

    $this->db->select('SEC_TO_TIME( SUM( TIME_TO_SEC( `duration` ) ) ) AS timeSum '); 
    $this->db->where('itemid',$id);
    $query = $this->db->get('duration');