Knowledge Base

How to connect to PostgreSQL using PHP

This article describes two methods for connecting to a PostgreSQL database using PHP:

  • PostgreSQL native functions
  • PDO (PHP Data Objects)
The PostgreSQL databases and users must already exist before you can use these methods. For information about how to manage PostgreSQL databases using cPanel, please see this article.

Connect to PostgreSQL using native functions

PHP provides many functions for working directly with PostgreSQL databases.

To connect to PostgreSQL using native functions:

  1. Use the following PHP code to connect to PostgreSQL and select a database. Replace USERNAME with your username, PASSWORD with your password, and DBNAME with the database name:
    <?php
        $db_connection = pg_connect("host=localhost dbname=DBNAME user=USERNAME password=PASSWORD"); 
    ?>
    
  2. After the code connects to PostgreSQL and selects the database, you can run SQL queries and perform other operations. For example, the following PHP code runs a SQL query that extracts the last names from the employees table, and stores the result in the $result variable:

    <?php
        $result = pg_query($db_connection, "SELECT lastname FROM employees");
    ?>
    

Connect to PostgreSQL using PDO (PHP Data Objects)

The PostgreSQL functions in the previous procedure can only be used with PostgreSQL databases. PDO abstracts database access, and enables you to use code that can handle different types of databases.

To connect to PostgreSQL using PDO:

  1. Use the following PHP code to connect to PostgreSQL and select a database. Replace USERNAME with your username, PASSWORD with your password, and DBNAME with the database name:
    <?php
        $myPDO = new PDO('pgsql:host=localhost;dbname=DBNAME', 'USERNAME', 'PASSWORD');
    ?>
    
  2. After the code connects to PostgreSQL and selects the database, you can run SQL queries and perform other operations. For example, the following PHP code runs a SQL query that extracts the last names from the employees table, and stores the result in the $result variable:

    <?php
        $result = $myPDO->query("SELECT lastname FROM employees");
    ?>
    

More Information