Drupal 7 Database Query examples

Public

Simple COUNT query

</> CopyGet raw version
php
  1. $num_matched_users = db_query("SELECT uid FROM users WHERE some_col <> ''")->rowCount();

Simple SELECT (non-alterable query)

</> CopyGet raw version
php
  1. $results = db_query('SELECT uid, name, mail FROM users');
  2. $users = array();
  3. foreach ($results as $result) {
  4. $users[] = $result;
  5. }

Simple UPDATE (set "name" col to "old_username" col, and then set "old_username" to empty string)

</> CopyGet raw version
php
  1. $affected_rows = db_update('users')
  2. ->expression('name', 'old_username')
  3. ->fields(array('old_username' => '' ))
  4. ->condition('old_username', '', '<>')
  5. ->execute();