我的数据库中有两个表;用户&朋友。我正在尝试获取与执行查询的用户是朋友的所有用户的信息。问题是我的php代码抛出了一个"命令不同步错误"。此外,我使用的代码看起来有点"黑客",如果有的话,还请建议其他选择。
在foreach循环之后的第二行中抛出错误。
我的代码:
$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);
我尝试了什么:
我试过使用
$stmt->store_result();
$stmt->close();
$con->next_result();
问题出现在foreach循环中。在循环结束时添加$stmt->close修复了问题。