I'm writing a module that will have to make a connection to a seperate database. In order for the user to configure the database, I'm allowing the user to fill out the database connection info in the module configuration form.

How can I test the database connection before submitting the form?

I added the relevant code below:

function mymodule_form($form, &$form_state) {
  //Form code omitted
  $form['#submit'][] = 'mymodule_form_submit';
  $form = system_settings_form($form);
  return $form;

function mymodule_form_validate($form, &$form_state){
  // Validation code, test db connection, need help here.

function mymodule_form_submit($form, &$form_state) {
  $values = $form_state['values'];
  $database = array(
    'database' => $values['database_name'],
    'username' => $values['database_username'],
    'password' => $values['database_password'],
    'host' => $values['database_host'],
    'driver' => $values['database_driver'],
  Database::addConnectionInfo('mymoduleDB', 'default', $database);

2 Answers 2


I don't see anything in Database or DatabaseConnection specifically. In a pinch you can just run a query that you know won't throw an exception in a Drupal site:

try {
  db_query('SELECT COUNT(nid) FROM {node}');
catch (\PDOException $e) {
  // Berate the user.
// PHP5.5+ only
finally {
  • Wouldn't I need to use another connection key for testing?
    – DenEwout
    Commented Apr 7, 2014 at 17:05
  • That's what db_set_active is for unless I've misunderstood what you mean?
    – Clive
    Commented Apr 7, 2014 at 17:08
  • Nevermind, i got it working. Thanks for the help, marked as correct answer.
    – DenEwout
    Commented Apr 9, 2014 at 14:33

Before I give you this potential solution this: Passing db info around unencrypted seems like a bad idea. other people may have a better idea of how to do this more securely.

Using hook_menu, you can create a function that accepts arguments via POST data.

Attach Javascript with your AJAX event using the forms API.

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.