I have two tables in my database; Users & friends. I am trying to fetch the information of all users which are friends with the user performing the query. The problem is that my php code is throwing a "commands out of sync error". Furthermore, the code I have used looks a bit "hacky", please also suggest some other alternative, if any.
The error is thrown in the second line after the foreach loop.
MY CODE:
$friends = [];
$query = "SELECT friend FROM friends WHERE register_id=? AND status=1";
$stmt = $con->prepare($query);
$stmt->bind_param("i",$register_id);
$stmt->execute();
$stmt->bind_result($_friend);
while($stmt->fetch())
array_push($friends,$_friend);
$stmt->close();
$query = "SELECT register_id FROM friends WHERE friend=? AND status=1";
$stmt = $con->prepare($query);
$stmt->bind_param("i",$register_id);
$stmt->execute();
$stmt->bind_result($_fri);
while($stmt->fetch())
array_push($friends,$_fri);
$stmt->close();
$con->next_result();
foreach($friends as $id){
$query="SELECT username,image,location FROM users WHERE register_id=?";
$stmt = $con->prepare($query);<----- Error thrown here
$stmt->bind_param("i",$id);
$stmt->execute();
$stmt->bind_result($_username,$_image,$_location);
$stmt->fetch();
$arr = [
'name'=>$_username,
'image'=>$_image,
'location'=>$_location,
];
$contacts[] = $arr;
}
sendJson(true,"Friends fetched successfully",$contacts);
WHAT I'VE TRIED:
I have tried to use
$stmt->store_result();
$stmt->close();
$con->next_result();