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.

Connecting to PostgreSQL using native functions

PHP provides many functions for working directly with PostgreSQL databases.

To connect to PostgreSQL using native functions, follow these steps:

  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");
    ?>
    

Connecting 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, follow these steps:

  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

Did you find this article helpful? Then you'll love our support. Experience the A2 Hosting difference today and get a pre-secured, pre-optimized website. Check out our web hosting plans today.

We use cookies to personalize the website for you and to analyze the use of our website. You consent to this by clicking on "I consent" or by continuing your use of this website. Further information about cookies can be found in our Privacy Policy.