Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Codeiginter: SQL join causing duplicate results [duplicate]

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

  • sub-category 1
  • Subcategory 2
  • Subcategory 3

Category 2

  • sub-category 4
  • sub-category 5
  • sub-category 6

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

  • sub-category 1

Category 1

  • sub-category 2

Category 1

  • sub-category 3

... 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"

  • id
  • title

Table "sub_categories"

  • id
  • title
  • categorie_id

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

like image 782
Dexception Avatar asked Jun 29 '26 21:06

Dexception


1 Answers

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
}
?>
like image 176
Captain Payalytic Avatar answered Jul 02 '26 10:07

Captain Payalytic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!