Avoid PDOException while connecting to an external database 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!
  }
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