I want to use a database query to grab all of a member's friends from a table in order to add the friend's email address to a form, to ready it for POSTing.

I am using the jquery ui, so on my form.php page, I have the script and html:

$(function() {
	$( "#friendsearch" ).autocomplete({
		source: "search.php",
		minLength: 2,
		select: function( event, ui ) {
			log( ui.item ?
				"Selected: " + ui.item.id + " " + ui.item.value :
				"Nothing selected, input was " + this.value );
    <input id="friendsearch" />
And on my search.php I have:

//code to connect to database.... etc

$query = "
    //this code goes through a table LEFT JOIN to grab a list of the logged-in member's friends' info (id, email, first name, last name)
$sql = mysql_query($query);
while($row = mysql_fetch_array($sql)) { 
	$fid = $row["id"];
	$firstname = $row["firstname"];
	$lastname = $row["lastname"];
	$email = $row["email"];

echo $fid <br /> $f_firstname <br /> $f_lastname <br /> $email <br /> ";
The "echo" above works. It lists out all the info perfectly, so I know my query is good. The problem, I am having, is with what comes next in the search.php:

$q = strtolower($_GET["term"]);

// supposed to do something with $q here (not sure what!)

$return = array();
    while ($row = mysql_fetch_array($query)) {
This is the part that's suppose to work with the jquery autocomplete. I know it's wrong, but I need to know how I can fix it to do the following:

1) when the user starts typing the first name or last name of the friend, auto-complete shows a drop-down list of firstname lastname.

2) once the friends' names are placed in the input box, on submit, i want to POST the friends' email addresses (not their name)!

Complex, I know... Any help would be much appreciated! Thanks,