Welcome Guest, Not a member yet? Register   Sign In
Generating "Categories and Subcategories"
#1

[eluser]Vasi[/eluser]
Hi guys,

I am pretty new to CodeIgniter, I need to extract a category->subcategory tree from my db, the table looks like this:

id
name
parent_id

My code looks like this:

Code:
class categories extends Model{

    function getCats(){
        $this->db->select('id,name');
          $this->db->from('categories');
          $this->db->where('parent =', 0);
          $q =$this->db->get();

        if ($q->num_rows()>0) {
            foreach($q->result() as $row) {
                $id = $row->id;
                $name_cat = $row->name;
                echo "<h4>" . $name_cat . "<h4><ul>\n";
                $sq = $this->db->query('SELECT name FROM categories WHERE parent = '.$id);
                if ($sq->num_rows()>0) {
                    foreach($sq->result() as $row_c) {
                        $name_subcat = $row_c->name;
                    echo "<li><a href='categorie/".str_replace(" ", "-", strtolower($name_subcat))."'>".$name_subcat."</a></li>\n";    
                    }
                }
                echo "</ul> \n";
                $data[] = $row;
            }
            return $data;
        }

    }

}

The problem is when I echo the $data in a view, I get the code posted at the beginning of the html document, so I can't integrate it in a template.

This is my first post and I feel like I haven't explained very well, I am sorry, please let me know if you need to know tell you anything else and if you can help me.

Thank you!
#2

[eluser]n0xie[/eluser]
Code:
$output .= "<h4>" . $name_cat . "<h4><ul>\n";
                $sq = $this->db->query('SELECT name FROM categories WHERE parent = '.$id);
                if ($sq->num_rows()>0) {
                    foreach($sq->result() as $row_c) {
                        $name_subcat = $row_c->name;
                    $output .= "<li><a href='categorie/".str_replace(" ", "-", strtolower($name_subcat))."'>".$name_subcat."</a></li>\n";    
                    }
                }
                $output .= "</ul> \n";
      
            }
            return $output;
#3

[eluser]Vasi[/eluser]
Thank you very very much!
I really appreciate it!
#4

[eluser]mddd[/eluser]
If I may give you some tips:

* You are manually making a url from the category name:
Code:
<a href='categorie/".str_replace(" ", "-", strtolower($name_subcat))."'>
It is much easier to use the url_title() function from the url Helper. This function does basically the same but will also check for characters that could mess up the url:
Code:
<a href="&lt;?=site_url('categorie/'.url_title($name_subcat))?&gt;">

* You are performing many queries, one for each main category. You could get all the categories in one go, and then loop through the results. That would make it easier on the database. (If the site traffic is low, that might not be relevant, I know).




Theme © iAndrew 2016 - Forum software by © MyBB