How to return last record from database in codeigniter?

22,878

Solution 1

Try this

$query = $this->db->query("SELECT * FROM date_data ORDER BY id DESC LIMIT 1");
$result = $query->result_array();
return $result;

Solution 2

For getting last record from table use ORDER BY DESC along with LIMIT 1

return $last_row=$this->db->select('*')->order_by('id',"desc")->limit(1)->get('date_data')->row();

Solution 3

You can do this as below code:

public function get_last_record(){
     $this->db->select('*');
     $this->db->from('date_data');
     $this->db->order_by('created_at', 'DESC'); // 'created_at' is the column name of the date on which the record has stored in the database.
     return $this->db->get()->row();
}

You can put the limit as well if you want to.

Solution 4

public function last_record()
{ 

    return $this->db->select('date_data')->from('table_name')->limit(1)->order_by('date_data','DESC')->get()->row();
}    

Solution 5

There is an easy way to do that, try:

public function last_record()
{ 
$query ="select * from date_data order by id DESC limit 1";
$res = $this->db->query($query);
return $res->result();
}
Share:
22,878
Rajan
Author by

Rajan

BY-DAY : I am a newbie programmer in a SIP-Telephony company. Developing PHP applications for them. BY-NIGHT: I learn new languages, like currently i am learning NODEJS. Other Interests: For passing my time i design Logo and do other graphics stuff in Adobe Photoshop,Illustrator and After Effects. Trying to explore the sea of programming and and design!

Updated on July 31, 2022

Comments

  • Rajan
    Rajan over 1 year

    I am trying to get the last date for which I have the data. So I want to print the last date in my column date_data.

    In Model:

    public function last_record()
    { 
        $query = $this->db->select('LAST(date_data)');
        $this->db->from('date_data');
        return $query;
    }
    

    In Controller:

    $last_data = $this->attendance_m->last_record();
    var_dump($last_data);
    

    But I am not getting the desired result

  • Rajan
    Rajan over 8 years
    Thanks a lot for your answer
  • Rajan
    Rajan over 8 years
    Thanks a lot for ur answer
  • Rajan
    Rajan over 8 years
    Thanks a lot for ur answer
  • Dylan B
    Dylan B over 6 years
    yah, this answer is great! Thanks