Connecting to PostgreSQL using PHP

Learn how to connect to PostgreSQL using PHP with this guide that includes detailed instructions for two methods: PostgreSQL native functions and PDO (PHP Data Objects).

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

  • PostgreSQL native functions.

  • PDO (PHP Data Objects).

👍

Tip

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

Related Articles