Don't use "SELECT * ". Specify the columns you want. This makes it easier for others, like me, to understand what is in the table and what the query is doing.
Indent your code to show the nested structure of loops etc.
If you had done those I might have given this problem more than a cursory glance. So you'll have to settle for a generic example of using a recursive function to give an indented list of parent/child elements.
Also,
Don't run queries inside loops. Use JOINs to get all the data in a single query
THE DATA
TABLE: category
+----+---------+--------+
| id | name | parent |
+----+---------+--------+
| 1 | happy | 0 |
| 2 | comet | 0 |
| 3 | grumpy | 0 |
| 4 | prancer | 1 |
| 5 | bashful | 1 |
| 6 | dancer | 2 |
| 7 | doc | 2 |
| 8 | blitzen | 2 |
| 9 | dasher | 3 |
| 10 | donner | 1 |
| 11 | vixen | 1 |
| 12 | cupid | 8 |
+----+---------+--------+
THE OUTPUT
THE CODE
<?php
$sql = "SELECT id, name, parent
FROM category";
$res = $db->query($sql);
//
// store arrays of items for each parent in an array
//
while (list($id, $name, $parent) = $res->fetch(PDO::FETCH_NUM)) {
$data[$parent][] = array('id'=>$id, 'name'=>$name);
}
/**
* recursive function to print a category then its child categories
*
* @param array $arr category data
* @param int $parent parent category
* @param int $level hierarchy level
*/
function displayHierarchy(&$arr, $parent, $level=0)
{
if (isset($arr[$parent])) {
echo "<ul>\n";
foreach($arr[$parent] as $rec)
{
echo "<li class='li$level'>{$rec['name']}\n";
if (isset($arr[$rec['id']]))
displayHierarchy($arr, $rec['id'], $level+1);
echo "</li>\n";
}
echo "</ul>\n";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Example</title>
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
</script>
<style type="text/css">
body { font-family: verdana,sans-serif; font-size: 11pt; padding: 50px; }
li { font-weight: 600;}
.li0 { color: red; }
.li1 { color: green; }
.li2 { color: blue; }
</style>
</head>
<body>
<?php
displayHierarchy($data, 0);
?>
</body>
</html>