0

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();
11
  • Possible duplicate of Commands out of sync; you can't run this command now Commented Apr 10, 2016 at 21:19
  • I have tried that. No dice. Same error. Commented Apr 10, 2016 at 21:20
  • You're saying you've made sure you've consumed all the results of the query in your foreach loop? Commented Apr 10, 2016 at 21:25
  • Is register_id the primary key of the users table? Commented Apr 10, 2016 at 21:26
  • 1
    I haven't really answered it, just provided a debugging suggestion. If you have managed to solve it post the solution as a self-answer to help other people in future. Commented Apr 10, 2016 at 21:39

1 Answer 1

2

The problem was in the foreach loop. Adding $stmt->close at the end of the loop fixed the problem.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.