Drupal - Get User Counts For Each User Role
Category:
Here is how to get a count of users for each user role in a Drupal 6 or 7 site:
SELECT COUNT(u.uid) AS user_count, r.name AS role FROM {users} u INNER JOIN {users_roles} ur ON u.uid = ur.uid INNER JOIN {role} r ON ur.rid = r.rid GROUP BY r.name ORDER BY user_count DESC;
(Note, this isn't the 'correct' way to do it in Drupal 7, we should really use the new Database API layer, but I'm lazy right now.)
This will give you a table something like this:
user_count | role |
3 | administrator |
7 | editor |
23 | author |
Here is a copy of the SQL query without Drupal's curly brackets:
SELECT COUNT(u.uid) AS user_count, r.name AS role FROM users u INNER JOIN users_roles ur ON u.uid = ur.uid INNER JOIN role r ON ur.rid = r.rid GROUP BY r.name ORDER BY user_count DESC;
Comments
Jon (not verified)
Fri, 10/12/2012 - 06:39
Permalink
Theoretically, you could put
Theoretically, you could put it anywhere where draupl runs php (even evaluated blocks with php code), but ideally, you should put this code into your module. When you start a new draupl website, you should always start at least one module to put all your custom functionality into it. For example, you might need this to run on hook_nodeapi (to respond to some draupl's event), or on hook_menu callback, or whatever you please.
tyler
Fri, 10/12/2012 - 14:26
Permalink
Agreed, starting at least one
Agreed, starting at least one custom module for each site is good practice, and code like this is best placed in there (or in a Drush script if we are feeling fancy).
shavin (not verified)
Thu, 02/20/2014 - 01:47
Permalink
It is quite hard to
It is quite hard to understand for begginers..u just use elaborate
tyler
Thu, 02/20/2014 - 09:09
Permalink
Hi Shavin,These are MySQL
Hi Shavin,
These are MySQL queries that can be executed inside a custom Drupal module. If you're new to using MySQL in Drupal, check out this page:
https://drupal.org/developing/api/database
angarsky (not verified)
Wed, 02/18/2015 - 08:05
Permalink
Drupal way Query is below :)
Drupal way Query is below :)