简体   繁体   中英

How to return last record from database in codeigniter?

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

Try this

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

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();

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.

public function last_record()
{ 

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

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();
}

Try this only with Active record

$this->db->limit(1);
$this->db->order_by('id','desc');
$query = $this->db->get('date_data');
return $query->result_array();

Try this to get last five record:

/**
* This method is used to get recent five registration
*/
public function get_recent_five_registration(){
    return $this->db->select('name')
    ->from('tbl_student_registration')
    ->limit(5)
    ->order_by('reg_id','DESC')
    ->get()
    ->row();
}

 $data = $this->db->select('*')->from('table')->where(id,$uid)->order_by('id',"desc")->limit(1)->get()->result();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM