Goose
Goose

Reputation: 4821

Codeigniter Active Record is only selecting the first record instead of the most recent

My problem is pretty simple. I'm using codeigniter active record, and all the model class has to do is select the most recent item from a table that belongs to the user.

function get_progress($users_id)
 {
  $query = $this->db->get('progress');
  $this->db->where('user_key', $users_id);
  $this->db->order_by("id", "desc");
  $this->db->limit(1);
  return $query->row_array();
 }

Seems simple, but for some reason, it's grabbing the lowest id that matches the user_key.

I've tried changing the where statement to

  $this->db->where('id', '2');

And it works, but of course, that's just for troubleshooting. I need variables.

I've rewritten few ways, including using get_where(), and changing desc to asc. No matter what, it's grabbing the low id. How can I select the highest id where user_key is the matching number.

Upvotes: 4

Views: 656

Answers (2)

sharad panchani
sharad panchani

Reputation: 21

function get_progress($users_id)
{
        $this->db->select('*')
        ->from('progress')
        ->where('user_key',$users_id)
        ->order_by('id','desc')
        ->limit(1);
        $q=$this->db->get();
        return $q->result_array();
}

Upvotes: 1

Touhid
Touhid

Reputation: 659

You can try the code below

function get_progress($users_id){
  return $this->db->from('progress')
  ->where('user_key', $users_id)
  ->order_by("id", "DESC")
  ->get()
  ->row();
}

You will get the last recent row as STD Class object

Upvotes: 1

Related Questions