I’ve quickly modified the original code so as to be recursive.
Please pay attention to the article that UFTimmy mentioned about hierarchical data as it’s a good one and will make things a lot easier for you in the future.
Disclaimer: The following has been worked from the provided code. It has not been tested. Do not use if allergic to peanuts. Lifejackets are to be found under your seat. Here be dragons.
function recurseMember($userid, $level=1) {
$result=@mysql_query("SELECT id,refid,firstname,lastname,email FROM members WHERE refid=$userid");
while($info=@mysql_fetch_object($result))
{
$userid=$info->id;
$refid=$info->refid;
$email=$info->email;
$nextname=$info->firstname." ".$info->lastname;
@mysql_query("INSERT INTO tmpdownline(userid,refid,name,email,level) VALUES($userid,$refid,'$nextname','$email',$level)");
}
// Get user
$result=@mysql_query("SELECT COUNT(*) AS cnt FROM members WHERE refid=$userid");
$count=@mysql_result($result,0);
if($count > 0) {
recurseMember($userid, $level + 1);
}
}
// Recursively query downline member
processMember($id);