Erinç Fırtına Erinç Fırtına - 1 month ago 7
MySQL Question

mysql database functions. I STUCK

I want to get user's friends then get their points. I coded 3 function for that. but i stuck at geting friends points.

Here is my code:

function GET_POINT($p_uid){
if($p_uid){
$user_info = mysql_query("SELECT * FROM user_list WHERE fid='{$p_uid}'");
while($row = mysql_fetch_array($user_info)) {
$point = $row['point'];
return $point;
}
}
}
function GET_FRIENDS($fl_uid){
if($fl_uid){
$friend_list_query = mysql_query("SELECT * FROM friend_list WHERE fid='{$fl_uid}'");
$friend_list = mysql_fetch_array($friend_list_query);
return $friend_list;
}
}
function GET_FRIEND_POINTS($fp_uid){
$friend_array = GET_FRIENDS($fp_uid);
$point = '0';
while($row = $friend_array){
$point += GET_POINT($row['fri_id']);
}
return $point;
}


what am i doing wrong?

Answer

The GET_FRIENDS only returns the first row:

function GET_FRIENDS($fl_uid){
   if ($fl_uid){
       $friend_list_query = mysql_query("SELECT * FROM friend_list WHERE fid='{$fl_uid}'");
       $friend_list = array();
       // fetch all rows and add them to our $friend_list array
       while ($row = mysql_fetch_array($friend_list_query)) {
          $friend_list[] = $row;
       }
       return $friend_list;
   }
}

Then you would need to update your code to loop through each element in the array:

function GET_FRIEND_POINTS($fp_uid){
   $friend_array = GET_FRIENDS($fp_uid);
   $point = 0;
   // loop through each element in the array - you should also check so the array
   // isn't empty before the loop
   foreach ($friend_array as $row) {
      $point += GET_POINT($row['fri_id']);
   }
   return $point;
}