How can I pass a parameter to a view if it is not in the URL? - Printable Version +- CodeIgniter Forums (https://forum.codeigniter.com) +-- Forum: Using CodeIgniter (https://forum.codeigniter.com/forumdisplay.php?fid=5) +--- Forum: General Help (https://forum.codeigniter.com/forumdisplay.php?fid=24) +--- Thread: How can I pass a parameter to a view if it is not in the URL? (/showthread.php?tid=70719) |
How can I pass a parameter to a view if it is not in the URL? - Ajax30 - 05-20-2018 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) { In the Categories controller I have added the line: Code: public function posts($category_id) { In the singe post view, where I already display the categories: Code: <?php foreach ($categories as $category): ?> 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? RE: How can I pass a parameter to a view if it is not in the URL? - jreklund - 05-20-2018 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 RE: How can I pass a parameter to a view if it is not in the URL? - Ajax30 - 05-21-2018 I don't have a forums table. My tables are:
Code: Message: Undefined variable: number_of_posts_by_category RE: How can I pass a parameter to a view if it is not in the URL? - jreklund - 05-21-2018 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. RE: How can I pass a parameter to a view if it is not in the URL? - shahnewaz - 05-21-2018 Try this, $this->load->view('categories/posts', $data); RE: How can I pass a parameter to a view if it is not in the URL? - Ajax30 - 05-21-2018 I already did: Code: $this->load->view('partials/header', $data); |