as someone that starting with PHP and mysql, here is a complete code example to get you what you want. there is no magic SQL here but a PHP loop (with a count limiter) to repeat asking the DB for the parent in the connection.
<?php
/* setup your database information */
$host = 'localhost';
$user = 'db_username';
$pass = 'db_password';
$db = 'db_name';
$link= mysqli_connect($host,$user,$pass,$db); // connect to the database
if (mysqli_connect_errno()) { // if fail connection... exit.
die(mysqli_connect_error());
}
/* the function to locate the first user in the chain of connections */
function find_first_user($link,$first,$last,$max_count=10){
$cnt=0; // local counter as prtection to never go over the $max_count
$parent=0;
$tbl='myTableName';
// find info about the person in question via the first & last name
$q="select parentUserId from $tbl where firstName='" . mysqli_real_escape_string($link, $first) .
"' and lastName='" . mysqli_real_escape_string($link, $last) . "'";
if($res=mysqli_query($link, $q)){
list($parent)=mysqli_fetch_row($res);
}
// if we found a parentId, repeat looking in the chain of connections
while($parent && ++$cnt<$max_count){
$q="select parentUserId,firstName,lastName from $tbl where userId=".intval($parent);
if($res=mysqli_query($link, $q)){
list($parent,$first,$last)=mysqli_fetch_row($res);
}
}
return "$first $last";
}
// example usage
print find_first_user($link,'Stephen','Lopez') . "\n";
?>