Database query in template.php Is it ok to query the database in a template.php file of a sub-theme. If not where do I put it? Below I have function that is querying the database and it works fine but I want to make sure I doing it the right way =).

function inTheTemplateFile() {
   $query = db_query("SELECT tid FROM taxonomy_menu");
   return  $query-&gt;fetchAll();
}
The template should idealy not be used to do database queries or other code that belongs in the Model or Controller of the MVC pattern.
The problem is that it is impossible to have a perfect implementation of the MVC pattern in Drupal.

What I mostly use as a rule of thumb is this:


Is this functionality that belongs to a module? Then put it in a module.
Would I have to copy this to a new theme if I made a second one? Then put it in a module (or parent theme if it should be in a subset of themes).
Does this function get/compute data or results which should be provided by a module? (like fetching user-data or a list of items) Then put it in a module.


In general the theme should only contain HTML, JS, CSS and a minimum of PHP used for simple loops, printing and simple conditional statements.

So the answer to your question would be; Probably not, it should probably be in a preprocess function or a getter function (like book_get_books()) in the module.

Edit: As Clive points out in the comments, Drupal does not strive to be fully MVC. The MVC pattern is only used to make it clear what belongs in the template, the controller and view don't really exist in drupal. Even the view is not as clear cut as it is in something like Symfony or Zend framework.