简体   繁体   中英

how can get last 10 record from table in codeigniter

i have controller that have function to get my post from table like this:-

function getPosts($user_id, $from, $to) {
    $this->db->order_by("ev_date", "DESC");
    $query = $this->db->get_where($this->table_name, array('ev_user_id'=>$user_id));

    return $query->result();
}

above function i can get all post from table but i need only display last 10 record from tabel.

the second problem the table " post " has user_id whos add this post, and store user_id, and when get all post i need to get the user name from " user " table.

the table user match with the post table by "User_id"

sounds like you need a join to get the user name, a join with codeigniter active record works like this:

$this->db->join('user', 'user.user_id = post.user_id');

you can use limit to limit your query

$this->db->limit(10);

source: CodeIgniter user manual

function getPosts($user_id, $from, $to) {
    $this->db->order_by("ev_date", "DESC");
    $query = $this->db->get_where($this->table_name, array('ev_user_id'=>$user_id), 10, 0);

    return $query->result();
}

From the CI docs.

$query = $this->db->get_where('mytable', array('id' => $id), $limit, $offset);
public function tenData()
{
    $query = $this->db
            ->order_by('id' , 'desc')
            ->limit(10)
            ->get('yourTable');

    return $query->result_array();
}

You can try this. order_by your id and add limit.

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