Three-level menu in php

Hello, there is a pluginof a three-level menu. I want to embed it in php, it doesn’t work. I have a Catalog table with id, parent, name fields. I could only do a two-level one, but I can’t prescribe the third cycle, I can’t solve it with recursion either, because it does not contain the correct location of tags

$tree_res = mysql_query("SELECT * FROM catalog WHERE parent= '0' AND checked='1' ORDER BY name");
while($menu_tree = mysql_fetch_assoc($tree_res))
{
?>
<li><a href="/catview.php?id=<?php echo $menu_tree['id'] ?>"><?php echo $menu_tree['name'] ?></a>
<?php
$sub_tree_res = mysql_query("SELECT * FROM catalog WHERE parent= ' ".$menu_tree['id']." ' AND checked='1' ORDER BY name ");
        if (!empty($sub_tree_res))
        {
?>
<ul>                        
<?php
while($sub_menu_tree = mysql_fetch_assoc($sub_tree_res))
  {
?>
<li><a href="/catalogview.php?id=<?php echo $sub_menu_tree['id'] ?>"><?php echo $sub_menu_tree['name']; 
$res = mysql_fetch_row(mysql_query("SELECT COUNT(*) FROM tovar WHERE Subdivision='$sub_menu_tree[id]' and checked='1'")); echo " <b>($res[0])</b>";  ?></a></li>
<?php
}
 ?></ul>
<?php
 }
}
 ?>
</ul>

Answer 1, authority 100%

I got your menu like this. True, it needs to be improved. I have nothing to check

function menu($id)
{
    $tree_res = mysql_query("SELECT * FROM catalog WHERE parent={$id} AND checked=1 ORDER BY name");
    while ($menu_tree = mysql_fetch_assoc($tree_res)) {
        echo "<li><a href='/catview.php?id={$menu_tree['id']}'>";
        echo "{$menu_tree['name']}</a><ul>";
        menu($menu_tree['id']);
        echo "</ul></li>";
    }
    return;
}
echo "<ul>";
menu(0);
echo "</ul>";

This is a 2nd level output. The third – just after each output, another reference to the function of checking goods.

PS And if you have different requests at all: both for the first level and for the second, then put each request in a separate function.