DEV Community

Cover image for Connecting to a PostgreSQL database in PHP
Luis Juarez
Luis Juarez

Posted on


Connecting to a PostgreSQL database in PHP

Connecting to a database is made much easier in PHP using the built in PDO class. PDO is a database abstraction layer. This allows us to connect to a database, then pass that connection to an object that we can later call.

To create a PDO object, you must pass in a Data source name, which is really just a string that sets the options for the connection.
Starting with the driver to use, then the host address, the database name, and if you want, a port number.

Important things to keep in mind:

  • set the driver in the DSN to pgsql for PostgreSQL.
  • your host will be relative to the server it is running on, so localhost or means the database is running on the same server the PHP file is being executed on

PHP Code to connect to a PostgreSQL database.

$databaseName = "";
$username = "";
$password = "";
$dsn = 'pgsql:host=;dbname=$databaseName';

try {
    //connect to the db
    $db = new PDO($dsn, $username, $password);

} catch (PDOException $e) {
    $error_message = $e->getMessage();
    echo $error_message;
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

An Animated Guide to Node.js Event Loop

Node.js doesn’t stop from running other operations because of Libuv, a C++ library responsible for the event loop and asynchronously handling tasks such as network requests, DNS resolution, file system operations, data encryption, etc.

What happens under the hood when Node.js works on tasks such as database queries? We will explore it by following this piece of code step by step.