Get The Topmost Parent's ID, Regardless of The Child's ID
02:20 10 Sep 2012

I have a table (eg the name is "page"), where each row is a child of another row, like below (see the HTML section):

http://jsfiddle.net/Fuqrb/

I want to find the topmost parent's id, by using a child's id. For example, we get a URL variable as the id of the bottommost child:

http://www.website.com/page.php?p=6

Then we store the URL variable into a variable:

$p = $_GET['p'];

To get the topmost parent's id, I have to use query function several times. For example:

if($result = $mysqli->query("SELECT * FROM page WHERE id='$p' LIMIT 1"))
{
    while($row = $result->fetch_array())
    {
        $parent = $row["parent"];
    }
}

if($result = $mysqli->query("SELECT * FROM page WHERE id='$parent' LIMIT 1"))
{
    while($row = $result->fetch_array())
    {
        $parent1 = $row["parent"];
    }
}

if($result = $mysqli->query("SELECT * FROM page WHERE id='$parent1' LIMIT 1"))
{
    while($row = $result->fetch_array())
    {
        $parent2 = $row["parent"];
    }
}

if($result = $mysqli->query("SELECT * FROM page WHERE id='$parent2' LIMIT 1"))
{
    while($row = $result->fetch_array())
    {
        $id = $row["id"];
    }
}

This way is ineffective, because if I got another URL variable as the id of another child of the higher/ lower level, this will not work.

How to get the topmost parent's id dynamically, regardless of the child's id?

php mysql loops parent-child