Friend of a friend script

hi everyone!
im trying to display a friend of a friend from a friend table,but i dont know how to do it. i have a table called friends,which has id,friendid and userid fields. Now i want if a member loggin, to be displayed a list of friends of his friends which are not his friends. i hope u u got me guys!im hopping to hear frm You.
below is what i tried to but it gave me infinite datas.


<?php
	   //Connect to the database server
 
    include"config.php";
    $user=$_SESSION['user'];
    $logged_id=$_SESSION['id'];
	//select all your friends
	$select=mysql_query("SELECT *FROM friends WHERE userid='$logged_id' ORDER BY RAND() LIMIT 2");
	$count_friends=mysql_num_rows($select);
	 if($count_friends>0){
	   while($r=mysql_fetch_array($select)){
	      $friendid=$r['friendid'];
		   //select friends of a friend except yourself and which ar not ur friends
		    $sqr=mysql_query("SELECT *FROM friends WHERE ((userid='$friendid') and (((userid !='$logged_id') or (friendid !='$friendid')) or (userid !='$friendid') or (friendid !='$logged_id')))");
			  while($raw=mysql_fetch_array($sqr)){
			      $friendoffriend=$raw['friendid'];
				  $_query = mysql_query("SELECT * FROM profile WHERE id = '$friendoffriend'");
                  $_row = mysql_fetch_array($_query);
                  $name=$_row['names'];
				  echo"$name fomt";
 
 
			  }
 
 
	}
	 }else{
 
	 echo"You must add friends";
 
	 } 
?>





Two levels of nested queries??? Your site will collapse as soon as there are multiple users on it at once!

You MUST learn SQL, specifically how to join tables, if you intend to build any kind of database driven website. I highly recommend Simply SQL. Friend of a friend is simply joining the friends table to itself.

Thank You for your suggestion but i have succeed in making it work.


include"config.php";
    $user=$_SESSION['user'];
    $logged_id=$_SESSION['id'];
	$sqr=mysql_query("SELECT friendid FROM friends WHERE userid IN (SELECT friendid FROM friends WHERE userid='$logged_id') AND friendid NOT IN (SELECT friendid FROM friends WHERE userid='$logged_id') ORDER BY RAND() LIMIT 10") or die(mysql_error());
	$countfriends=mysql_num_rows($sqr);

if($countfriends>0){
    THE WHILE LOOP HERE
  AND DISPLAY


}else{
 echo"I SUGGEST YOU SHOULD ADD FRIENDS";

}