On Drupal 8, I have this line inside my form (my_module/src/Form/MyCustomForm.php).

$users = db_query('SELECT * FROM {users}');

var_dump($users) shows an object (of my query) and not the list of all users.

object(Drupal\Core\Database\Statement)[322] public 'dbh' => object(Drupal\Core\Database\Driver\mysql\Connection)[20] protected 'needsCleanup' => boolean false protected 'target' => string 'default' (length=7) protected 'key' => string 'default' (length=7) protected 'logger' => null protected 'transactionLayers' => array (size=0) empty protected 'driverClasses' => array (size=0) empty protected 'statementClass' => string 'Drupal\Core\Database\Statement' (length=30) protected 'transactionSupport' => boolean true protected 'transactionalDDLSupport' => boolean false protected 'temporaryNameIndex' => int 0 protected 'connection' => object(PDO)[15] protected 'connectionOptions' => array (size=10) 'database' => string 'theming' (length=7) 'username' => string 'root' (length=4) 'password' => string 'private' (length=8) 'prefix' => array (size=1) ... 'host' => string 'localhost' (length=9) 'port' => string '3306' (length=4) 'namespace' => string 'Drupal\Core\Database\Driver\mysql' (length=33) 'driver' => string 'mysql' (length=5) 'pdo' => array (size=4) ... 'init_commands' => array (size=1) ... protected 'schema' => null protected 'prefixes' => array (size=1) 'default' => string '' (length=0) protected 'prefixSearch' => array (size=2) 0 => string '{' (length=1) 1 => string '}' (length=1) protected 'prefixReplace' => array (size=2) 0 => string '' (length=0) 1 => string '' (length=0) public '_serviceId' => string 'database' (length=8) public 'allowRowCount' => boolean false public 'queryString' => string 'SELECT * FROM users' (length=19) 


1 Answer 1


There's nothing different from 7.x with db_query(), it returns a result set where you can fetch results from or loop over it. Refer to the database API documentation.

However, there are even less reasons for doing a direct database query in 8.x than in 7.x, and doing the query by hand is very likely going to be more complicated because of the data tables.

Use entity query instead:

$uids = \Drupal::entityQuery('user')

Executing an entity query always returns entity IDs which can then be loaded:

$users = \Drupal::entityManager()->getStorage('user')->loadMultiple($uids);
// Shorthand if you know that you have users:
$users = \Drupal\user\Entity\User::loadMultiple($uids);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.