Morgan Klaif
Morgan Klaif

Reputation: 75

PHP - MySQL Query, Show User Only Once

Good evening,

I am trying to alter some code from a user panel which includes user roles. I would like certain roles to display the user for each role they're in, but certain roles I only want them shown once.

The MySQL table being used for this is:

id | username | password | displaygroup | usergroups
1  | User A   | Pass A   | 2            | 1,2,3
2  | User B   | Pass B   | 5            | 1,2,3,4,5

For example, if User A is in groups 1, 2 and 3, they should be listed three times for each group they're a part of. Once a user is in a higher group, like User B, I only want them shown once, in their highest group.

The old queries that were being used were:

$query = $db->query("SELECT * FROM users WHERE displaygroup = '2' ORDER BY id");
while ($array = $db->assoc($query)) {
  echo $array['username'];
}

With that query, User A would only show once.

I have tried the following:

$query = $db->query("SELECT * FROM users ORDER BY id");
while ($array = $db->assoc($query)) {
  $role = explode(',', $array['usergroups']);
  foreach ($role as $value) {
    if ($value == 1) {
      echo $array['username'];
    }
    if ($value == 2) {
      echo $array['username'];
    }
  }
}

With the above, it works perfectly fine for User A, as it shows them for groups 1, 2 and 3 that they're in.

However, User B is now showing up, since they are also in those roles.

How can I get it so User A continues to show for groups 1, 2 and 3, and User B only shows for group 5?

UPDATE

There seems to be confusion in my question. I pretty much want it to do:

Group 1
User A

Group 2
User A

Group 3
User A

Group 4

Group 5
User B

Upvotes: 0

Views: 78

Answers (1)

partho222
partho222

Reputation: 81

You can reverse the role array and check from the last value. If higher value like 5 exist do your operation and break the loop.

$query = $db->query("SELECT * FROM users ORDER BY id");
while ($array = $db->assoc($query)) {
  $role = explode(',', $array['usergroups']);
  $role = array_reverse($role);
  foreach ($role as $value) {
    if($value == 5) {
        echo $array['username'];
        break;
    }
    if ($value == 1) {
      echo $array['username'];
    }
    if ($value == 2) {
      echo $array['username'];
    }
  }
}

Upvotes: 2

Related Questions