How to connect then fetch data from online database to drupal 8 on localhost. Both of them using postgre as main database. I have followed this tutorial and change settings.php's external host with ip from my online database. I try to fetch data with my module, refer to this but still not work, my module look like this:

namespace Drupal\example\Controller;

class ExampleController {

  public function example() { 

    // Get a connection going
    $db = \Drupal\Core\Database\Database::getConnection();

$query = $db->select('users', 'u')
    ->fields('u', ['name', 'email']);
$result = $query->execute()->fetchAll();



I was edited this code, looks more simple, and now showing result

pgsql The website encountered an unexpected error. Please try again later.

this result only showing result from print_r($db->databaseType); but i still confuse, is this come from external database? Thank's for some help of this case.

  • Have you tried connecting with another client? Usually databases are configured to only allow local connections. If so, you won't be able to connect externally. – rovr138 Mar 22 '17 at 4:15
  • What does "still not work" mean exactly? – Clive Mar 22 '17 at 7:49
  • @Clive I have update my code and showing the result. Before this only showing blank page with unstoppable reload proses, that's I mind "still not work". – Ugy Astro Mar 22 '17 at 8:25
  • Can you provide the error message from the PHP error log? – mradcliffe Mar 22 '17 at 11:50
  • @mradcliffe thank's for suggest to add PHP error log, I really sorry about this, finally found and fix this error. Variable connection that I use is not same with variable connection that I declare. Now i can access my online database in my localhost. I hope this can be useful when we need data from another db although it has different host. – Ugy Astro Mar 23 '17 at 3:02

Your Answer

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

Browse other questions tagged or ask your own question.