Drupal 7 Form API, Checkboxes with key -> value from database I'm working on a custom module and I'm adding a form that uses checkboxes.  All is fine with using code like: 

$form['tags'] = array(
   '#type' => 'checkboxes',
    '#options' => array(
      88 => 'option1',
      100 => 'option 2',
      79 => 'etc'
    ),
   '#title' => t('Tag this project as...'),
  );

The problem comes from the fact that I'd like to pull the key and value from the database (a specific taxonomy).  I do not want to use an autocomplete, I want to use checkboxes.  

Specifically, how do I get the results from the database and format into a proper array for the options array?  Also, on the edit version of the form I'm creating, how do I show items that have been "checked" based on their value? 

All of the examples I've seen are extremely basic and never show how to do this from a database call.  Thanks for reading/answering
To populate your options array with data from table my_table, with value keys from column value and text from column atext, you can use:

$options = array();
$result = db_select('my_table', 'mt')
            -&gt;fields('mt', array('value', 'atext'))
            -&gt;execute();
foreach ($result as $row) {
  $options[$row-&gt;value] = $row-&gt;atext;
}


To get taxonomy terms, you could use the code above to query tid and name from the taxonomy_term_data table (plus add a condition() for the vocabulary id), but for this specific usage you'd better to use the right API:

$options = array();
// Get term tree for vocabulary which id is in $vid.
$terms = taxonomy_get_tree($vid);
foreach ($terms as $term) {
  $options[$term-&gt;tid] = $term-&gt;name;
}


Just do not forget that vocabularies are tree structures. See the documentation for the taxonomy_get_tree() API to know how to limit the terms you want to get from a vocabulary wrt starting term and tree depth.