Welcome Guest, Not a member yet? Register   Sign In
How can I pass a parameter to a view if it is not in the URL?
#1

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:

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?
Reply
#2

You need to make a LEFT JOIN in your function that you return in $data['categories'].
Code:
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
Reply
#3

(This post was last modified: 05-21-2018, 01:39 PM by Ajax30.)

I don't have a forums table. My tables are:
  • posts
  • categories
  • users
  • comments
How would you actually solve the problem: 
Code:
Message:  Undefined variable: number_of_posts_by_category
Reply
#4

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.
Reply
#5

Try this,

$this->load->view('categories/posts', $data);
Smile
Reply
#6

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




Theme © iAndrew 2016 - Forum software by © MyBB