Passing variable from one function to another

Absolute beginner in PHP, so please be patient.

I am trying to use the $friends variable from function getFriends() in the getFriendsById () function, but even when I tried declaring $friends as global, it doesn’t work.

I recieve the following 2 error messages:

Notice: Undefined property: User::$friends
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given.

Any advice please.

[php]
function getFriends(){
$sql=“select friend_id from user_friends where user_id =” .$this->user_id;
$results = mysql_query($sql);
$friends = array();
$this->friends = $friends;
while ($row = mysql_fetch_array($results)){
$friends[] = $row[‘friend_id’];
}

		return $friends;
	}
	
	/* This is the function which must use the friends id's to extract the names
	and surnames of the friends from the "users" table in the database and return values*/
		
public function getFriendsById() {
	$sql="SELECT first_name, last_name FROM user WHERE user_id =". $this->friends;
	$results = mysql_query($sql);
	$friendsNames = array();
	while ($row = mysql_fetch_array($results)){
		$friendsNames[] = $row["first_name, last_name"];
		}
	return $friendsNames;
}

}	

[/php]

hope this helps :smiley:
[php]$friends=getFriends();
getFriendsById($friends);[/php]

Thank you for the quick responce.

I am really a beginner, where should I place your code? Like this??

[php]
function getFriends(){
$sql=“select friend_id from user_friends where user_id =” .$this->user_id;
$results = mysql_query($sql);
$friends = array();
$this->friends = $friends;
while ($row = mysql_fetch_array($results)){
$friends[] = $row[‘friend_id’];
}

		return $friends;
	}
	
	/*This is the function which must use the friends id's to extract the names
	and surnames of the friends from the "users" table in the database" and return values*/
		
public function getFriendsById($friends) {
	$sql="SELECT first_name, last_name FROM users WHERE user_id =". $friends=getFriends();
	$results = mysql_query($sql);
	$friendsNames = array();
	while ($row = mysql_fetch_array($results)){
		$friendsNames[] = $row["first_name, last_name"];
		}
	return $friendsNames;
}

}	

[/php]

Got it working.

Thank you!!

I love this response!! I hope you learned something about functions and how to use them with this experience!!!

just by writing

function{ some code }
this does not actually run the function it is just defining the function and what it should do when it is ran!!
so then you have to run the function here is two way to do it
[php]$friends=getFriends();
getFriendsById($friends);[/php]
the first one runs the function and fills the variable with the result, the second one just runs the function and returns the result.

you are PHP GOD.

Thanx!! Your explanation helps alot. Unable to + your karma. Perhaps disabled for neewbs like me?

Sponsor our Newsletter | Privacy Policy | Terms of Service