I am trying to get my all categories and sub-categories from MySQL database in a hierarchy:
My result should be like that (just example):
Try the following code
//connect to mysql and select db
$conn = mysqli_connect('localhost', 'user', 'password','database');
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 '';
echo '- ' . $row->cat_name;
category_tree($row->id);
echo '
';
$i++;
if ($i > 0) echo '
';
endwhile;
}
//close the connection
mysqli_close($conn);
?>
More...