How do I select a table using a variable with db_query()?
This is one of the reasons the new query builder exists in Drupal 7, so you can dynamically substitute parts of the query:

$table_name = 'the_table';
$field_name = 'a_field';
$query = db_select($table_name)-&gt;fields($table_name, array($field_name));


Using db_query() you only get parameter replacement, which would only be applicable to substitutions in WHERE conditions. This means that you cannot use db_query() to replace table names, the names of fields selected, etc., only WHERE conditions.

Have a look at the db_select() docs for more in-depth examples, including how to add conditions to the dynamic query.