phpcodeignitersql-updatequery-builderdatediff

How to update a column value using the day difference between two dates with MySQL and CodeIgniter's query builder


I need to get the difference of two dates and update the difference of the dates in the database.

model

public function approve($id, $leave_type, $leave_start, $leave_end) 
{   
    $diffDays= abs($leave_end - $leave_start);  
    $this->db->set('leave_days', $diffDays);
    $this->db->set('status', Approved);
    $this->db->where('id', $id);
    $this->db->update('leave');

    return $this->db->affected_rows() > 0;  
}

abs($leave_end - $leave_start); is not working. But when a hardcoded value is set to diffDays, it works fine.

Details about my schema:

CREATE TABLE leave (
  id int(11) NOT NULL,
  user_name text NOT NULL,
  user_id int(11) NOT NULL,
  leave_type varchar(255) NOT NULL,
  leave_start date NOT NULL,
  leave_end date NOT NULL,
  leave_days int(11) NOT NULL,
  status text NOT NULL
)
ENGINE=InnoDB DEFAULT CHARSET=latin1; 

INSERT INTO leave (id, user_name, user_id, leave_type, leave_start, leave_end, leave_days, status) VALUES
(121, 'Harry Potter', 6, 'Casual', '2018-06-28', '2018-06-29', 0, 'Approved'),
(122, 'Harry Potter', 6, 'Annual', '2018-06-22', '2018-06-25', 0, 'Approved'),
(123, 'Harry Potter', 6, 'Casual', '2018-06-23', '2018-06-25', 4, 'Approved');

Solution

  • Adjust the date format to the format you are using.

        $leave_start = DateTime::createFromFormat('Y-m-d', $leave_start);
        $leave_end = DateTime::createFromFormat('Y-m-d', $leave_end);
        $diffDays = $leave_end->diff($leave_start)->format("%a");
    
        $this->db->where('id', $id);
        $this->db->update('leave', array('leave_days' => $diffDays));