I have a drupal with many external databases. I do the same things in all databases but I want to limit the access to the database basing on the role the logged-in user has.

I mean:

  • The administration user has access to all databases
  • Employee has access to db1 and db2
  • Worker has access to db1

How can I control database access per role?

  • I guess you mean by role, not by roll. – kiamlaluno Sep 13 '15 at 6:34

If you mean controlling which database Drupal uses for its own database tables (e.g. the table containing all the registered users, the active sessions, the nodes created), then it is not possible. There is no way to tell Drupal which database use basing on the user's roles.

If you are asking about your own module, then it is possible, but your module needs to handle this on its own because Drupal doesn't have my specific functions to handle your use case, except the following ones:

  • user_has_role() checks the user account passed as argument (or the currently logged-in user) has the role passed as argument

  • db_set_active() set the database used from the successive database API calls using one of the keys set in the settings.php file

Rather than using db_set_active(), I would use $options['target'] which can be used from any Drupal function necessary to query the database.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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