Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

recursive function category database

i hoping to create a recursive function which i don't have an idea yet

this is my code to fetch category from database

  <?php
  $sql = mysql_query("SELECT * FROM categories WHERE category_parent = '1' ORDER BY lft ASC");
  while($row = mysql_fetch_array($sql)) {
  echo "<li><a href='/{$row['category_safe_name']}/'>{$row['category_name']}</a>";
  $sql2 = mysql_query("SELECT * FROM categories WHERE category_parent = '{$row['category_id']}'");
  if(mysql_num_rows($sql2) > 0)
  echo "<ul>";
  while($row2 = mysql_fetch_array($sql2)) {
  echo "<li><a href='/{$row2['category_safe_name']}/'>{$row2['category_name']}</a><li>";
  }
  if(mysql_num_rows($sql2) > 0)
  echo "</ul>";
  echo "</li>";
  }
  ?>

Currently This look like

Top Category (category_id = 1)
   Category
       Sub Category

My code works for category & subcategory. What i'm planning to do is to make my code to support unlimited subcategories

Any help and advise are welcomed.

Thank you

like image 909
damien Avatar asked Sep 25 '26 11:09

damien


1 Answers

I would do :

<?php
function getChildren($id=1) {
  $sql = mysql_query("SELECT * FROM categories WHERE category_parent = '$id' ORDER BY lft ASC");
  echo "<ul>";
  while($row = mysql_fetch_array($sql)) {
    echo "<li><a href='/{$row['category_safe_name']}/'>{$row['category_name']}</a>";
    getChildren($row['category_id']);
    echo "</li>";
  }
  echo "</ul>";
}

getChildren();
?>
like image 131
Toto Avatar answered Sep 28 '26 00:09

Toto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!