Recursive function database

I hope to create a recursive function that has no idea yet

this is my code to retrieve a category from a 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 it looks like

Top Category (category_id = 1)
   Category
       Sub Category

My code works for categories and subcategories. I plan to have my code support unlimited subcategories

Any help and recommendations are appreciated.

thank

+3
source share
4 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();
?>
+3
source

You should look at hierarchical data management in MySQL .

It gives a good overview of some approaches to using hierarchical data in MySQL.

+2
source

, . , , . :

function getCategories($parent=0) {
    $res = mysql_query("SELECT * FROM categories WHERE category_parent = '$id' ORDER BY left ASC");
    if (mysql_num_rows($res) > 0) {
        $category = mysql_fetch_object();
        echo '<ul>';
        echo '<li><a href="' . $category->category_safe_name . '">' . $category->category_name . '</a>';
        getCategories($category->category_id);
        echo '</li>';
    }
}

- , , , .

0
source

Something like that?

function getCategories($mid, $categoryParent = 1)
{
    $return = '';
    $results = mysql_query("SELECT * FROM categories WHERE category_parent = '$categoryParent' ORDER BY lft ASC", $mid);
    while($row = mysql_fetch_array($results)) {
        $return .= "<li><a href='/{$row['category_safe_name']}/'>{$row['category_name']}</a></li>";
        $subs = getCategories($mid, $row['category_id']);
        if (!empty($subs)) {
            $return .= '<ul>';
            $return .= $subs;
            $return .= '<ul>';
        }
    }
    return $return;
}

$mid = mysql_connect($host, $user, $pass);
echo getCategories($mid);

Print all of your categories, of course, correct them exactly the way you want, but this should give you an idea of ​​how recursive functions can work.

-1
source

Source: https://habr.com/ru/post/1755776/


All Articles