I am working on a blog application in Codeigniter 3.1.8 and Bootstrap 4.
The posts can be filtered by categories. I want to display the number of posts in each category.
The categories table in the database looks like this:
For this purpose, I have done the flowing:
In the Posts_model model I have added the function:
Code:
public function get_num_rows_by_category($category_id) {
$query = $this->db->get_where('posts', array('cat_id' => $category_id));
return $query->num_rows();
}
In the Categories controller I have added the line:
Code:
public function posts($category_id) {
// More code
// More code
$data['posts'] = $this->Posts_model->get_posts_by_category($category_id, $limit, $offset);
$data['number_of_posts_by_category'] = $this->Posts_model->get_num_rows_by_category($category_id);
$this->load->view('partials/header', $data);
$this->load->view('categories/posts');
$this->load->view('partials/footer');
}
In the singe post view, where I already display the categories:
Code:
<?php foreach ($categories as $category): ?>
<a href="<?php echo base_url('/categories/posts/'.$category->id); ?>" class="list-group-item list-group-item-action">
<span class="text-muted"><?php echo $category->name; ?></span>
<span class="badge badge-secondary badge-pill"><?php echo $number_of_posts_by_category; ?></span>
</a>
<?php endforeach; ?>
The problem with this approach is that the $category_id variable (representing the category' s id) is not passed via the single post page URL. So there is this error:
Code:
Message: Undefined variable: number_of_posts_by_category
What options do I have?