I am writing a configuration entity modul in drupal 9. I want to list all tables, from an external database (postgis) in the schema called gi. The switch between the databases is no problem. I'm searching for a way, to only get the name of the table called gruenzuege to put this in a markup form.

//the form where to save the table

 $form['tables'] = [
      '#type' => 'fieldset',
      '#title' => $this->t('Tables'),
      '#collapsible' => TRUE, // Added
      '#collapsed' => FALSE,  // Added

//External Database connection

$postgis_database = array(
      'database' => $drugis_postgis_connection->getdatabase(),
      'username' => $drugis_postgis_connection->getusername(),
      'password' => $drugis_postgis_connection->getpassword(),
      'host' => $drugis_postgis_connection->gethost(),
      'driver' => 'pgsql'
Database::addConnectionInfo('postgis', 'default', $postgis_database);
Database::setActiveConnection('default', 'postgis');

//example for fetching table:gruenzuege in drupal

    $results = Database::getConnection('default', 'postgis')->query('SELECT * FROM "gi"."gruenzuege"')->fetchAll();

I don't understand how to query to another schema, to get only, the table names of the schema gi? It is actually the only table. Thanks for help

  • Welcome to Drupal Answers :) This sounds like a question about SQL rather than Drupal - if not please could you edit and make clear what the Drupal part of it is? Thanks!
    – Clive
    Sep 28 at 18:09
  • Sorry, i hope it is clearer now
    – Steffen
    Sep 28 at 19:00

listing all table names in an array

$example_database = array(
      'database' => ...,
      'username' => ...,
      'password' => ...,
      'host' => ...,
      'driver' => 'pgsql'

Database::addConnectionInfo('example_key', 'default', $example_database);
Database::setActiveConnection('default', 'example_key');

$result=Database::getConnection('default', 'example_key')->query("SELECT table_name FROM information_schema.tables WHERE table_schema = '" . example_schema . "';");
  $tables = $result->fetchAll();

foreach( $tables as $table ) {
      $tableNames[] = $table->table_name;

  • As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
    – Community Bot
    Oct 2 at 6:52

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.