I am creating a friend list using mysql and php. My problem is that only one result is showing up, even though there are two friends for the user i am testing with. my code look as follows:
<?php
if (isset($_POST['tag']) && !empty($_POST['tag'])) {
$tag = $_POST['tag'];
require_once 'DB_Functions.php';
$db = new DB_Functions();
$response = array("tag" => $tag, "success" => 0, "error" => 0);
if($tag == 'friend_id_tag') {
$uuid = $_POST['uuid'];
if($db->userExists($uuid)) {
$data = $db->getFriendList($uuid);
if($data != false) {
$response["success"] = 1;
$response["friend"] = $data["name"];
echo json_encode($response);
}else {
echo "No existing user";
}
} else {
echo "No existing user";
}
}
}
?>
and the mysql query
<?php
class DB_Functions {
private $db;
//put your code here
// constructor
function __construct() {
require_once 'DB_Connect.php';
// connecting to database
$this->db = new DB_Connect();
$this->db->connect();
}
// destructor
function __destruct() {
}
function getFriendList($uuid) {
$result = mysql_query("SELECT name FROM Account WHERE unique_id IN(SELECT friend_id FROM FriendList WHERE player_id = '$uuid' AND is_friends = 1)");
$no_of_rows = mysql_num_rows($result);
if ($no_of_rows > 0) {
$result = mysql_fetch_array($result);
return $result;
} else {
return false;
}
}
function userExists($uuid) {
$result = mysql_query("SELECT * FROM Account WHERE unique_id = '$uuid'");
$no_of_rows = mysql_num_rows($result);
if ($no_of_rows > 0) {
// user existed
return true;
} else {
// user not existed
return false;
}
}
}
?>
You should run while loop in function
function getFriendList($uuid) {
$result = mysql_query("SELECT name FROM Account WHERE unique_id IN(SELECT friend_id FROM FriendList WHERE player_id = '$uuid' AND is_friends = 1)");
$no_of_rows = mysql_num_rows($result);
if ($no_of_rows > 0) {
$d = array();
while($data = mysql_fetch_array($result)){
$d[] = $data;
}
return $d;
} else {
return false;
}
}
Your getFriendList returns an array $data = $db->getFriendList($uuid);
but this part is not looped
if($data != false) { $response["success"] = 1;
$response["friend"] = $data["name"]; echo json_encode($response); }else {
So that would just set $response['friend'] to the first user only.
UPDATE: added loop
if($data != false) { $response["success"] = 1; for($i = 0; $i < count($data); $i++) { $response["friend"][$i] = $data[$i]["name"]; } echo json_encode($response); }else {