emcee22
emcee22

Reputation: 1889

get the last row in the db

What is the correct way to retrieve the last row, sorted desc by id, in CodeIgniter? I've tried select_max but I want the whole row.

function getLastPagination(){
    $data = array();
    $this->db->query("SELECT id,sort FROM pagination GROUP BY id DESC LIMIT 1");
    $query = $this->db->get('pagination');
    $data = $query->row_array();
    return $data;
}


$data['allpag'] = $this->Model_cats->getLastPagination();
$data['pagin'] = $data['allpag']['sort'];
$per_page = $data['pagin'];  

Here I am getting the first value, but I want the last row.

Upvotes: 2

Views: 22552

Answers (3)

Alex Shuraits
Alex Shuraits

Reputation: 442

$this->db->select('id')->order_by('id','desc')->limit(1)->get('table_name')->row('id');

Upvotes: 9

Venkata Krishna
Venkata Krishna

Reputation: 4305

Try this.............

function getLastPagination(){

     $query ="select * from pagination order by id DESC limit 1";

     $res = $this->db->query($query);

     if($res->num_rows() > 0) {
            return $res->result("array");
    }
    return array();
    }
}

In controller function you need to do following things.......

$allpag = $this->Model_cats->getLastPagination();
$per_page = $allpag[0]['sort'];

Upvotes: 6

Mudshark
Mudshark

Reputation: 3253

$query = $this->db->query("SELECT * FROM pagination ORDER BY id DESC LIMIT 1")->row_array();

Should work?

Upvotes: 0

Related Questions