I am trying to expand my knowledge, and building a mini-forum. Though, i have a problem with my code.
On the forum index page, i would like to display all the forum-categories with sub-categories, like this:
Category 1
Category 2
As you see, it's kinda the normal "forum-style".
But, when i'm fetching the results from th database, it's returning duplicate resultat. In this case, duplicate "Forum categories". So it looks like this:
Category 1
Category 1
Category 1
... and so on
Here is my Model that fetches all the categories etc: categories.php
function GetCategories()
{
$this->db->select('*, categories.title as cat_title')->from('categories')-> join('sub_categories', 'sub_categories.categorie_id = categories.id');
$categories = $this->db->get();
print_r($categories->result());
return $categories;
}
and my Forum controller:
function index()
{
$data['categories'] = $this->categories->GetCategories();
$this->load->view('forum/index', $data);
}
And the view
<div class="forum-body">
<?php
foreach($categories->result() as $cate)
{
echo '<div class="categorie-head">'.$cate->cat_title.'</div>';
?>
<div class="categories-body">
<?php echo $cate->title;?>
</div>
<?php
}
?>
Table structure
Table "catgories"
Table "sub_categories"
So, what is the easiset wa yto fix it? Is it possible with onlly one query?
Please let me know if you don't understand :)
Try this:
<div class="forum-body">
<?php
$cat_title = '';
foreach($categories->result() as $cate)
{
if($cat_title != $cate->cat_title)
echo '<div class="categorie-head">'.($cat_title = $cate->cat_title).'</div>';
?>
<div class="categories-body">
<?php echo $cate->title;?>
</div>
<?php
}
?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With