返回对应于一个给定值的多个值[关闭]

I have this table in mysql database

number     | name         | friend
-------------------------------
1          |John          | Kloey
2          |John          | Tara
3          |Marco         | Tia
4          |John          | Clara

I need to get all the names in the friend column that corresponds to john in name column in an array or a string or anything that i can then receive in android? How can i do this?

Here's my php code but it just returns the 1st name which is kloey only

$username = $_POST["username"];
$recordofusername = mysql_query("SELECT * FROM friends WHERE name='$username'");
$value1 = mysql_fetch_array($recordofusername);
$user_friendname = $value1['friend'];
$response["userfriends"] = $user_friendname;

 echo json_encode($response);
  1. Please don't use deprecated mysql_* extension.
  2. Don't interpolate query strings leaving your code vulnerable to sql injections. Learn and use prepared statements with either mysqli_* or PDO
  3. When you get the resultset which contains more then one row you should iterate over the resultset to fetch all the rows, which you didn't in your code. And that's why with your code you always get the only one name from the first row in the resultset.
  4. Don't use SELECT *. Instead explicitly tell what columns you need to select. In your case you just need friend column.

That being said to give you an idea how your code might look like using mysqli

$name = $_POST['username'];
$friends = array();
$db = new mysqli('localhost', 'user', 'password', 'dbname');
if (!$db) {
    die('Could not connect: ' . $db->connect_error); //TODO: better error handling
}
$sql = "SELECT friend FROM friends WHERE name = ?";
if ($stmt = $db->prepare($sql)) {
    $stmt->bind_param('s', $name);
    $stmt->execute();
    $stmt->bind_result($friend);

    while ($stmt->fetch()) { // you have to iterate over the resultset
        $friends[] = $friend;
    }
    $stmt->close();
} else {
    die('Prepare failed: ' . $db->error); //TODO: better error handling
}
$db->close();

$response['userfriends'] = $friends;
echo json_encode($response); 

Sample output:

{"userfriends":["Kloey","Tara","Clara"]}