Category Hierarchy (PHP/MySQL)

后端 未结 5 1452
悲&欢浪女
悲&欢浪女 2020-11-29 20:57

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):

5条回答
  •  抹茶落季
    2020-11-29 21:42

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

提交回复
热议问题