Recursive category tree in php and mysql

Sometime you face problem in php to manipulate hierarchical data. This code will show you that how to display category tree in php. Here Mysql database used to store data. I have used here recursive method which search data in n Level . for example level 1 , level 2 , level 3 , level N…. as on. This simple code will work for multiple level as par your requirement. For example level 0 have ‘year’ category and its subcategory has ‘Jan’ ,’Feb’ as on.

Mysql table sample data used in this code.


Complete php code for generate recursive category tree output.

<?php //connect to mysql and select database $conn = mysqli_connect('localhost', 'rootuser', 'rootpwd','corephp'); if( !empty($conn->connect_errno)) die("Error " . mysqli_error($conn));

//call the recursive function to print category listing

//Recursive php function
function category_tree($catid){
global $conn;

$sql = "select * from category where parent_id ='".$catid."'";
$result = $conn->query($sql);

while($row = mysqli_fetch_object($result)):
$i = 0;
if ($i == 0) echo '
 echo '
<li>' . $row->cat_name;
 echo '</li>

 if ($i > 0) echo '</ul>

//close the connection

Output will shows as follows


so you see that how to resolved this problem with recursive function.

Enjoy Coding !!



5 thoughts on “Recursive category tree in php and mysql

  1. hello, i found this post on google: first perfect recursive post in the net and also with msqli statment. Thank you very much. Really usefull. But i have to ask a little question about this. If you want use only parent_id = 0, inside a float div. How can i do?

    1. Hi I need a chart like structure for the same DB structure and PHP code how it can be achieved by CSS please help me…,

      Please check the below image exactly I need the same with above DB structure.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s