DEV Community

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

Posted on

4 2

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

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Heroku

This site is powered by Heroku

Heroku was created by developers, for developers. Get started today and find out why Heroku has been the platform of choice for brands like DEV for over a decade.

Sign Up

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay