phpmysqlcodeignitermaxresultset

How to get max(id) in CodeIgniter


I want to get the maximum id of row data. In my table first column is id then firstname and etc. this is the sql command I used to get the max(id) of row data.

$maxid = $this->db->query("SELECT MAX(id) FROM `emplyee_personal_details`");
print_r($maxid);

but it prints bunch of data as it is a array. But I need only the maximam id of row data for validation before data inserting and updating.

How can I get the max id? I use the CodeIgniter framework.


Solution

  • Try this:

    $maxid = $this->db->query('SELECT MAX(id) AS `maxid` FROM `emplyee_personal_details`')->row()->maxid;
    

    UPDATE

    This will work even if your table is empty (unlike my example above):

    $maxid = 0;
    $row = $this->db->query('SELECT MAX(id) AS `maxid` FROM `emplyee_personal_details`')->row();
    if ($row) {
        $maxid = $row->maxid; 
    }