Pass variables from custom module to its template? I'm trying to query my DB, and return those values as variables, then print those variables on my custom module's custom template and I can't get it to work.

If I put this into my theme layer it works fine.

$name=db_result(db_query('SELECT name FROM {users} WHERE id = %d', 2));
print $name;


I'd rather keep my queries in the .module file and only have to print the variable on my template. So far I haven't been successful.
Also, since I'm planning on having many variables used in many places (like display tables, or as values in calculations) I'd rather be able to print variables where I need them, and not tie them to an $output, or $content variable.

I referenced this post but I couldn't get the example to work.

I'm really new at this, my experience so far as only to take form info and save it to the DB, not bringing it back. so I'd appreciate any help.
To use the theme API it requires three portions: the template file, the theme hook, and then displaying the defined theme. The below examples are for Drupal 7.

&lt;?php
  // defines the theme hook - should follow the naming format "_theme()"
  function mymodule_theme(){
    return array(
      'example_template1' =&gt; array(
        'template' =&gt; 'mytemplatefile1', // mytemplatefile1.tpl.php
      ),
      'example_template2' =&gt; array(
        'template' =&gt; 'mytemplatefile2', // mytemplatefile2.tpl.php
      ),
    );
  }

  // in this function is where you would do your DB queries,
  // and pass to the theme function as shown
  function mymodule_customfunction(){
    $calculation = 1+1;
    return theme('example_template1', array(
      'example_variable1' =&gt; $calculation,
      'example_variable2' =&gt; '123',
    ));
  }
?&gt;


The mytemplatefile1.tpl.php file could look something like this:

&lt;div class="example-markup"&gt;&lt;?php echo $example_variable1; ?&gt;&lt;/div&gt;


To display your output, you could then just execute the following and it would print your value, wrapped in the "example-markup" div.

&lt;?php echo mymodule_customfunction(); ?&gt;