Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Hierarchical Data from Database

Tags:

php

mysql

mysqli

Hello i have one stupid question. But maybe is not. In database i have table categories and i have 4 cols Id, parent_id, title and description. Parent_id is child of current category.

Id |  parent_id |  title  |  description

___________________________________________________

1  |     1      | Main Category | description 


2  |     1      | Sub Category  | description 


3  |     2      | Other Category | description 

4  |     1      | Some Category | description 

Ok i know how to input data and show results; that is not problem. When i show result in table

<table>
   <tr>
        <td> Id </td>
        <td> Parent </td>
        <td> Title </td>
        <td> Desc </td>
   </tr>
    <?php foreach($categories as $category): ?>
    <tr>
       <td> <?php echo $category->id; ?> </td>
       <td> <?php echo $category->parent_id; ?> </td>
       <td> <?php echo $category->title; ?> </td>
       <td> <?php echo $category->eescription; ?> </td>
   </tr>
   <?php endforeach;?>
</table>

This works great and shows child categories under under the other parent categories : Table looks like this:

1  |     1      | Main Category | description 
2  |     1      | Sub Category  | description   
3  |     2      | Other Category | description    
4  |     1      | Some Category | description 

My problem is how to list all category and sub category like this

    |-- Main Category
       |--- Sub Category 
           |--- One more cat  

   |--Other Category   
      |--- Some Category

Like this enter image description here

Is it possible to fetch this data using forach() ? Any example how to do this.

Thanks

like image 906
Jony Avatar asked Aug 24 '26 15:08

Jony


2 Answers

Read about this http://www.sitepoint.com/hierarchical-data-database-2/. Should solve your issue.

like image 67
Eugene Avatar answered Aug 27 '26 04:08

Eugene


I do this. Am working on Codeigniter framework. If any need this i will post how i fix this like on screenshot.

Just simple make model :

Model

   /*
    * Get all children categories
    * 
    * Get Hierarchical Data from Categories
    * 
    * @ikac
    */

   public function fetchChildren($parent, $level) {


       $this->handler = $this->db->query("SELECT * FROM content_categories WHERE parent='".$parent."' ");


          foreach($this->handler->result() as $row) {
             echo str_repeat('&nbsp; &nbsp; &nbsp; &nbsp; |-----', $level).$row->title .'<br>';

             $this->fetchChildren($row->title, $level+1);
          }

   }

}

Like output u will get

Default
     |-----Sub Category
     |-----Test Category 1
           |-----Seccond Test Category 1

Thanks @Eugene

like image 41
Jony Avatar answered Aug 27 '26 06:08

Jony



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!