, , ,

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.

//connect to mysql and select db
$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 '<ul>';
 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 !!