PHP

[Solved] How to Show All Users in MySQL Database in PHP

Updated

Show All Users in MySQL Database in PHP

There is no SHOW USERS statement in MySQL. Typing it gets you a syntax error, on 8.4.10 and on every version before it:

mysql> SHOW USERS;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'USERS' at line 1

Accounts live in an ordinary table, so you query it like one — SELECT User, Host FROM mysql.user; — and from PHP that is a plain SELECT:

<?php
$pdo = new PDO('mysql:unix_socket=/tmp/mysql.sock;charset=utf8mb4', 'reporting_user', $password, [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES   => false,
]);

$rows = $pdo->query(
    'SELECT User, Host, account_locked, password_expired
     FROM mysql.user ORDER BY User, Host'
)->fetchAll();

printf("%-18s %-10s %-7s %-8s\n", 'USER', 'HOST', 'LOCKED', 'EXPIRED');
foreach ($rows as $r) {
    printf("%-18s %-10s %-7s %-8s\n",
        $r['User'], $r['Host'], $r['account_locked'], $r['password_expired']);
}

Run against a live 8.4.10 server, that prints:

USER               HOST       LOCKED  EXPIRED
hw_su_app          localhost  N       N
hw_su_expired      localhost  N       Y
hw_su_locked       localhost  Y       N
hw_su_readonly     %          Y       Y
mysql.infoschema   localhost  Y       N
mysql.session      localhost  Y       N
mysql.sys          localhost  Y       N
root               localhost  N       N

Do not grant SELECT on the whole mysql schema

Do not fix a permissions error with GRANT SELECT ON mysql.* TO 'username'@'host';. It hands the account every password hash on the server. Measured — after that exact grant, a user with no other privileges read another account’s credentials:

+---------------+-----------------------+----------------------+----------+
| User          | plugin                | hash_prefix          | hash_len |
+---------------+-----------------------+----------------------+----------+
| hw_su_expired | caching_sha2_password | $A$005$Tf*52u};fybu  |       70 |
+---------------+-----------------------+----------------------+----------+

That is an offline cracking target, and it is a much bigger privilege than “let the dashboard list accounts”. Grant the four columns you actually read instead:

GRANT SELECT (User, Host, account_locked, password_expired)
  ON mysql.user TO 'reporting_user'@'localhost';

The listing above was produced by a PHP script connecting as exactly that account. Asking for one column outside the grant is refused:

ERROR 1143 (42000): SELECT command denied to user 'hw_su_app'@'localhost' for column 'authentication_string' in table 'user'

With no grant at all, the failure is 1142 rather than 1143 — worth distinguishing when you are debugging: ERROR 1142 (42000): SELECT command denied to user 'hw_su_app'@'localhost' for table 'user'.

Following the grant with FLUSH PRIVILEGES; is unnecessary. GRANT updates the in-memory grant tables directly; per the MySQL 8.4 manual on when privilege changes take effect, FLUSH PRIVILEGES is only for when you have modified the mysql tables with raw INSERT/UPDATE. Every grant on this page took effect on the next connection without one.

Roles are in the same table, disguised as locked accounts

This is the one that makes account audits wrong. CREATE ROLE does not create a separate object — it creates a row in mysql.user that is locked with an expired password. In the listing above, hw_su_readonly is a role, not a user, and nothing in User, Host, account_locked or password_expired tells you so. Note also that account_locked = 'Y' is the normal, correct state for the built-in mysql.infoschema, mysql.session and mysql.sys accounts — a locked account is not automatically a finding.

What the flags do mean is enforced at login. A locked account fails with its own error code:

ERROR 3118 (HY000): Access denied for user 'hw_su_locked'@'localhost'. Account is locked.

An expired password does not deny access; it puts the session into sandbox mode, where the only statement allowed is one that sets a new password. The command-line client reports it as: Please use --connect-expired-password option or invoke mysql in interactive mode. Every error above can be provoked again with four test accounts, and mysql-show-users-in-php.sh does exactly that on a MySQL 8 server that accepts mysql -u root: it creates three users and a role, runs both PHP listings against them, then drops all four without touching any existing account.

USER() and CURRENT_USER()

USER() is the username and host the client supplied at connect time. CURRENT_USER() is the account row MySQL matched and is checking privileges against. They usually agree, and did here:

+----------------+----------------+
| USER()         | CURRENT_USER() |
+----------------+----------------+
| root@localhost | root@localhost |
+----------------+----------------+

They diverge when a wildcard host entry matches, when proxy users are in play, or inside a DEFINER-context routine. Both work with no privileges at all, so SELECT CURRENT_USER(); is the right first query when you are trying to work out why an account cannot see something. SHOW GRANTS; with no arguments also works unprivileged and shows the current account’s own grants.

Who is connected right now

The information_schema.processlist view still returns rows on 8.4.10, but it raises a deprecation warning:

Warning | 1287 | 'INFORMATION_SCHEMA.PROCESSLIST' is deprecated and will be removed in a future release. Please use performance_schema.processlist instead

Use the Performance Schema view, the replacement the manual’s own page for the deprecated view tells you to use:

SELECT user, host, db, command FROM performance_schema.processlist;
+-----------------+-----------+------+---------+
| user            | host      | db   | command |
+-----------------+-----------+------+---------+
| event_scheduler | localhost | NULL | Daemon  |
| root            | localhost | NULL | Query   |
+-----------------+-----------+------+---------+

Note that this lists connections, not accounts — an account with no open connection does not appear, which is why it is no substitute for reading mysql.user.

If you must build the query dynamically

Filtering by host from a web request is the obvious next step and the obvious injection. Bind it:

$stmt = $pdo->prepare('SELECT User, Host FROM mysql.user WHERE Host = ?');
$stmt->execute([$_GET['host']]);

The mysqli equivalent, which also runs clean on PHP 8.5.8, uses mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); so failures throw instead of returning false, then prepare() and bind_param('s', $host). Identifier positions — a schema or table name — cannot be bound at all; those must be checked against an allowlist you control, never interpolated from input.

Photo of author
Sudhir P. founded HeatWare.com in 1999 and has built and operated it full-stack ever since; it is now used by more than 88,000 people. He writes here about the PostgreSQL, MySQL, Linux and DevOps work that keeps it running. Articles are rewritten only after the commands in them have actually been run, and the verification scripts are published alongside them so anyone can check the claims. Reach him at blog@heatware.net.