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);
mysql_*
extension.mysqli_*
or PDO
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"]}