CodeIgniter Forums

Full Version: How can I pass a parameter to a view if it is not in the URL?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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.

[Image: pBGlD.png]

The categories table in the database looks like this:

[Image: Z2IJ4.png]

For this purpose, I have done the flowing:

In the Posts_model model I have added the function:

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:

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);

In the singe post view, where I already display the categories:

<?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>
<?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:

Message:  Undefined variable: number_of_posts_by_category

What options do I have?
You need to make a LEFT JOIN in your function that you return in $data['categories'].
SELECT categories.*,count(forums.category_id) AS number_of_posts FROM categories LEFT JOIN forums ON forums.category_id=categories.category_id GROUP BY categories.category_id
I don't have a forums table. My tables are:
  • posts
  • categories
  • users
  • comments
How would you actually solve the problem: 
Message:  Undefined variable: number_of_posts_by_category
Replace it with posts then. It's just an example...

And that's how I would solve it, with a join. As it will only require one query instead of X, where X are are the number of categories you have. Your application will run slow if you make multiple queries instead of utilizing joins.
Try this,

$this->load->view('categories/posts', $data);
I already did: 
$this->load->view('partials/header', $data);