I am working on an online newspaper/blogging application with CodeIgniter 3.1.8 and Bootstrap 4.
At the bottom of the single post view, I want to add a link to the next post (as well as one to the previous post). For this, I need to get the data (slug, title, etc), of the next post (row in the posts
table).
For this purpose, I have added this method to my Posts_model model:
/* Next post */ public function get_next_post($slug) { $query = $this->db->get_where('posts', array('slug' => $slug)); if ($query->num_rows() > 0) { $data = $query->next_row(); return $data; } }
In the controller I have:
public function post($slug) { //more code $data['post'] = $this->Posts_model->get_post($slug); $data['next_post'] = $this->Posts_model->get_next_post($slug); print_r($data['next_post']); //more code }
EDIT: In the Posts_model, I now have:
/* Next post */ public function get_next_post($slug) { $query = $this->db->get('posts'); $row_index = 6; $data = $query->row_array($row_index); if ($query->num_rows() > 0) { $data = $query->next_row(); return $data; } } /* Prev post */ public function get_prev_post($slug) { $query = $this->db->get('posts'); $row_index = 6; $data = $query->row_array($row_index); if ($query->num_rows() > 0) { $data = $query->previous_row(); return $data; } }
That means that if I could get the current post’s index by slug, I could replace this hardcoded index of the 7th post – $row_index = 6
– and the problem would be solved.
How do I do that?
Advertisement
Answer
// Your_model.php ... public function getPost($slug) { $this->db->where('slug', $slug); return $this->db->get('posts_table')->row_array(); } public function getPrevPost($currentPostId) { $this->db->where('id <', $currentPostId); $this->db->order_by('id', 'desc'); $this->db->limit(1); return $this->db->get('posts_table')->row_array(); } public function getNextPost($currentPostId) { $this->db->where('id >', $currentPostId); $this->db->limit(1); return $this->db->get('posts_table')->row_array(); } // Yourcontroller.php ... public function getPost($slug) { $post = $this->your_model->getPost($slug); $data = [ 'thePost' => $post, ... 'prevPost' => $this->your_model->getPrevPost($post['id']), 'nextPost' => $this->your_model->getNextPost($post['id']), ... ]; ... }