1

I'm trying to connect to another database (not related to drupal) in drupal to show extra info. This database server could be down and is not a problem, if it's the case I don't want to show the info with no errors, maybe an info message that is now available at this moment.

I setted up the settings.php correctly with the database credentials, and when the database is up, everything is ok.

I use the next code

  db_set_active('external');
  $query = db_select('extra_info', 'i');
  ...

If the database is down, the db_select() fails and throws an PDOException. The problem is the website is down in that case, shows the error and so on. I tryed to sorround it in a try catch.

  try {
      db_set_active('external');
      $query = db_select('extra_info', 'i');
      ...
  }
  catch (PDOException $e) {
      // Ok.. is not a problem
  }

I don't know if there is a way to check if the database connection is ok first and then do the select or do nothing if is there is a problem and continue showing the website. I tried the isActiveConnection() function, but I think is not what I need.

Thanks.

EDIT: The solution to my problem is to use db_set_active() back to default.

  try {
      db_set_active('external');
      $query = db_select('extra_info', 'i');
      ...
      db_set_active(); // This won't be executed!
  }
  catch (PDOException $e) {
      // Ok.. is not a problem
      db_set_active(); // Needed!
  }

1 Answer 1

3

issue is that db_set_active just sets active key in some array and doesn't do any connection. when you do db_select or any other query only then it connects.

your second code is good. also you could do something like this:

  db_set_active('external');
  try {
   //check connection
   db_select("select 1");
  }
  catch (PDOException $e) {
      //error. set default back
      db_set_active('default');
  }

as you know how to check if connection is there now you just need extra logic what todo when connection cannot be established

2
  • Thanks @MantasKaranauskas I was getting an Uncaught exception 'PDOException' because I forgot to add db_set_active() in the catch section. I updated the first post with the solution to my specific problem. Commented May 6, 2014 at 11:05
  • 1
    To test connection, select 1 from dual or simply select 1 is safer as it does not require any particular table to exist to work. See description of DUAL pseudotable.
    – Mołot
    Commented May 6, 2014 at 12:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.