Tags

, , ,


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 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
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 !!