Home > database >  How to connect to PostgreSQL databases from php?
How to connect to PostgreSQL databases from php?

Time:09-29

I'm trying to connect to a pgadmin database. I've replaced NAME, IPADDRESS, USERNAME and PASSWORD below.

$dsn = 'mysql:dbname=NAME;host=IPADDRESS';
        $user = 'USERNAME';
        $password = 'PASSWORD';

        try {
            $dbh = new PDO($dsn, $user, $password);
            $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        } catch (PDOException $e) {
            echo 'Connection failed: ' . $e->getMessage();
        }

But it times out

Fatal error: Uncaught PDOException: SQLSTATE[HY000] [2002] Operation timed out in

What could this mean? Is this the right way to connect to postgreSQL databases from php?

CodePudding user response:

Please try to add pgsql: in connection string like below example

$dbh = new PDO('pgsql:host=IPADDRESS;dbname=NAME', 'USERNAME', 'PASSWORD');

You can also get the reference from the below URL

https://www.a2hosting.in/kb/developer-corner/postgresql/connect-to-postgresql-using-php

  • Related