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.

php-mysql-category-tree

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
category_tree(0);

//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 '
<ul>';
 echo '
<li>' . $row->cat_name;
 category_tree($row->id);
 echo '</li>

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

';
endwhile;
}
//close the connection
mysqli_close($conn);
?>

Output will shows as follows

php-mysql-category-tree

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

Enjoy Coding !!

 

Published by PHP Technology Tutorials

PHP Developer

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 comment