我有一系列权限组,例如Admin,Moderator等...我想查询SQL数据库并检索这些组的人数...这是我的代码:
$groups = $this->getGroupsUsingPermission("sabre.access");
foreach($groups as $g) {
$command = "SELECT COUNT(PERMISSION_GROUP) FROM users
WHERE PERMISSION_GROUP='".$g."';";
$query = mysqli_query($this->connection, $command) or die (mysqli_error());
$amountOfStaff = $amountOfStaff + mysqli_fetch_row($query)[0];
}
除了一遍又一遍地查询数据库之外,还有更好的方法吗?
更新
我是这样的意思:
groups:
member:
permissions:
- sabre.access
admin
permissions:
- sabre.admin
inheritance:
- member
现在,我有这个工作,以及继承。它返回一个数组:
member, admin (any other groups which have access to 'sabre.access' etc...)
所以当我像这样设置某个人的小组时:
ID, USERNAME, PERMISSION_GROUP
1 KraZ Owner
我想要算上阵列中任何一个群体的人,你能得到我吗?
答案 0 :(得分:5)
使用MySQL的IN()
一次搜索所有群组:
$groups = $this->getGroupsUsingPermission("sabre.access");
$group_ids = implode("','", $groups)
$command = "SELECT COUNT(PERMISSION_GROUP) FROM users WHERE PERMISSION_GROUP IN('".$group_ids."');";
$query = mysqli_query($this->connection, $command) or die (mysqli_error());
$amountOfStaff = $amountOfStaff + mysqli_fetch_row($query)[0];
这里我使用implode()
获取组ID并使它们成为逗号分隔的字符串。然后我将这个值传递给IN()
。你也可以在这里使用FIND_IN_SET()
。
$groups = $this->getGroupsUsingPermission("sabre.access");
$group_ids = implode(',', $groups)
$command = "SELECT COUNT(PERMISSION_GROUP) FROM users WHERE FIND_IN_SET(PERMISSION_GROUP, '".$group_ids."');";
$query = mysqli_query($this->connection, $command) or die (mysqli_error());
$amountOfStaff = $amountOfStaff + mysqli_fetch_row($query)[0];
答案 1 :(得分:0)
你不想要每组中的用户数量吗?
$groups = $this->getGroupsUsingPermission("sabre.access");
$group_ids = implode(',', $groups)
$command = "SELECT PERMISSION_GROUP, COUNT(*) userCount FROM users
WHERE PERMISSION_GROUP IN (".$group_ids.")
Group By PERMISSION_GROUP";
$query = mysqli_query($this->connection, $command) or die (mysqli_error());
$amountOfStaff = $amountOfStaff + mysqli_fetch_row($query)[0];