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 127.0.0.1 means the database is running on the same server the PHP file is being executed on

PHP Code to connect to a PostgreSQL database.

<?php
$databaseName = "";
$username = "";
$password = "";
$dsn = 'pgsql:host=127.0.0.1;dbname=$databaseName';

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

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

Top comments (0)