It's actually pretty easy. Write a recursive function that takes an ID as an argument. The function should build a (global) string, working right to left. If the parent ID is zero, then you have a root item and the string should be printed. If the parent ID isn't zero, the function calls itself and passes the parent ID as an argument.
Essentially you're printing "bread crumb trails" for each object in your database. Here is a function that I use in my message board system:
// Print a breadcrumb trail from 0 to this location $id
function breadcrumbs($id)
{
global $roomid;
global $db;
global $prattle_rooms;
global $breadcrumbtrail;
$result = mysql_db_query($db, "select * from $prattle_rooms where
roomid='$id'");
$room = mysql_fetch_object($result);
if ($id == $roomid)
$breadcrumbtrail = $room->title;
else
$breadcrumbtrail = "<a href=\"prattle.php?roomid=$room->roomid\">$room->title</a> > $breadcrumbtrail";
if ($room->roomparent) breadcrumbs($room->roomparent);
return $breadcrumbtrail;
}
And the result looks something like this:
Lobby > Geekstuff: Talk about Linux, PHP, MySQL, et cetera > PHP-Flash-talk