[development] new dev q: are mysql queries possible within drupal?

larry at garfieldtech.com larry at garfieldtech.com
Wed Nov 18 23:34:27 UTC 2009


spartaguy spartaguy wrote:
> 
> Thanks to everyone that replied.
> 
> 
> To summarise then:
> 
>  1)  I need to make a custom module.
>  2) The module should have a block for displaying the query and a menu hook
>  3) I can add the module to either primary links or navigation as a menu 
> item
>  4) Rendered HTML using mysql commands is quite straight forward
>  5) The tables being queried are easier to access within the main drupal 
> d/b but i can use a different db
>  
> 
> Regarding a different db, does this command:
> 
> db_set_active('customerdb');
> 
> make *all* db queries go through customerdb or just the ones for my module?
> ie will drupal have any issues accessing the data it needs from say 
> "drupaldb" if I dont change
> the active db back again?

db_set_active('customdb'); will make *all* queries run against customdb, 
until you call db_set_active(); to set it back to the default DB.  For 
that reason, you should minimize the amount of work you do while using 
that DB.  For instance:

function dostuff() {

   $old_db = db_set_active('custom');

   $data = db_fetch_object(db_query("SELECT ..."));

   db_set_active($old_db);

   // Do some manipulation of $data here.

   return theme('mytheme_key', $data, $something_else);
}

Note that in the above, you put all of your DB interaction together in 
one place, switch the DB just long enough to run that, and then go back 
to normal.  That ensures that once you get into theme calls or calling 
other Drupal functions you're back on the main Drupal database so that 
other code doesn't get confused.

--Larry Garfield


More information about the development mailing list