用户表如下:
uid Name address
1 Ravi Rajasthan
2 Kamal Bihar
3 Sunil Rajasthan
4 Laxman Punjab
组表如下:
gid gname users
1 group1 1,3,4
2 group2 2,4
我正在使用此代码。
$sql = "SELECT groups.uid,groups.group_name FROM users
INNER JOIN users ON users.uid=groups.uid";
$query = $dbh -> prepare($sql);
$query->execute();
$results=$query->fetchAll(PDO::FETCH_OBJ);
//$resul = explode(",", $results)
$cnt=1;
foreach($results as $result){
echo '<br>';
$getids = (explode(',', $result->uid));
foreach ($getids as $getid) {
//echo $getid . '<br>';
$id = $getid;
$sql = "SELECT user_name FROM users WHERE uid=:id";
$query = $dbh -> prepare($sql);
$query->bindParam(':id',$id, PDO::PARAM_STR);
$query->execute();
$results=$query->fetchAll(PDO::FETCH_OBJ);
foreach($results as $result) {
echo $result->user_name . ', ' ;
}
}
}
?>
有人可以向我解释吗?我很难理解。 谢谢
答案 0 :(得分:-1)
要获取每个组的所有用户的列表,可以使用单个SQL 查询:
SELECT
groups.uid, groups.group_name,
users.uid, users.user_name
FROM groups
INNER JOIN users ON users.uid IN(groups.users)