how to return a db_query as an option list and display it &lt;?php

/**
 * Define callbacks that can be used as custom select list options.
 */
function webform_contacts_webform_select_options_info() {
  $items = array();

  if (function_exists('webform_options_contacts')) {
    $items['contacts'] = array(
      'title' =&gt; t('Contact List'),
      'options callback' =&gt; 'webform_options_contacts',
    );
  }

  return $items;
}

/**
 * Option list containing Contacts.
 * Pull a list of users where status=active and rid=5 from database.
 */
function webform_options_contacts() {
  $items = array();

  $query = db_query("SELECT realname.realname AS realname_realname, realname.uid AS realname_uid, users.uid AS uid, 'user' AS field_data_field_gal_phone_user_entity_type FROM {users} users INNER JOIN {users_roles} users_roles ON users.uid = users_roles.uid LEFT JOIN {realname} realname ON users.uid = realname.uid WHERE (( (users.status &lt;&gt; '0') AND (users_roles.rid = '5') )) ORDER BY realname_realname ASC");

  $results = $query-&gt;execute();
}


I created a custom module for displaying an extra option list. The example provided by Drupal 7 Webform Cookbook I used worked; using a hard coded list and it displays fine. 

I want to use a db_query to populate the list. I have this code (shown above) but am unable to see anything displayed. Help! I am sure I am missing the command to properly get this to display as a list.
You can make use of DatabaseStatementInterface::fetchAllKeyed(), but as you only need 2 columns it would be wise to change your query slightly. Essentially you want to select just one for the identifier, and one for the label. Something like this:

$sql = ' 
    SELECT realname.uid, realname.realname 
    FROM {users} users 
    INNER JOIN {users_roles} users_roles ON users.uid = users_roles.uid 
    LEFT JOIN {realname} realname ON users.uid = realname.uid 
    WHERE users.status &lt;&gt; :status AND users_roles.rid = :rid
    ORDER BY realname.realname';

$args = array(':status' =&gt; 0, ':rid' =&gt; 5);

return db_query($sql, $args)-&gt;fetchAllKeyed();


That will return an array with the 1st column (uid) as keys and the 2nd column (realname) as values, which you can use verbatim as options for a form element.

You don't have to return just 2 columns from the query, as fetchAllKeyed() allows you to specify the index for both key and value; but as you're not using the data for anything else, it makes sense to avoid the overhead of the extra columns.

Slightly unrelated: you shouldn't call exceute() on the return from db_query(), as the query has already been executed by that point. You can either use one of the helper methods like fetchAllKeyed(), or iterate directly over the values, e.g. 

foreach (db_query($sql) as $row) {
  // ...