Dynamic Select Query On Another DB
Add external database name in settings.php(../sites/all/default/settings.php) file of your project. You can set databse in settings.php as follows:  

$databases = array (
  'default' =&gt; 
  array (
    'default' =&gt; 
    array (
      'database' =&gt; 'drupal_db',
      'username' =&gt; 'root',
      'password' =&gt; '',
      'host' =&gt; 'localhost',
      'port' =&gt; '8080',
      'driver' =&gt; 'mysql',
      'prefix' =&gt; '',
    ),
  ),

  'external' =&gt; 
  array (
    'default' =&gt; 
    array (
      'database' =&gt; 'external_db',
      'username' =&gt; 'root',
      'password' =&gt; '',
      'host' =&gt; 'localhost',
      'port' =&gt; '8080',
      'driver' =&gt; 'mysql',
      'prefix' =&gt; '',
    ),
  ),
);


And you can directly add your query in files.