I want to display parent child hierarchy on a web page using PHP.
I am using recursion for that but relationship is not being displayed correctly.
I have a table in database with 3 fields:
id, parent_id, name
child which doesn't have any parent has 0 as parent id.
So I call the below given function with id of 0 to start displaying hierarchy.
Parent and child are displayed in correct order but indenting by using "-" is not.
$level = 1;
$query = "select * from categories where parent_id=$parent_id";
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result))
echo "<option value=\"". $row['id'] . "\">";
echo $parent_id . " ". $row['id']. " ". $level;
for ($i=0; $i <= $level; $i++)
echo $row['name'] . "</option>";
$level += 1;
$level = 1;
I have solved this problem by adding a new field in table called level which stores, at the time of addition, the level in the hierarchy a category has. For example if a parent has level of 4 then child will have level 5 and so on.
Problem is that when I change parent of a child level of all the children of this child also has to be changed.
I want a solution where no additional field "level" is stored in the table and level is determined at the time of displaying the hierarchy.
1. Is it possible to do it by using only one query and using recursion.
2. Is there any way to do it without recursion.