How to Use PostgreSQL in PHP

Updated: January 13, 2024 By: Guest Contributor Post a comment

Introduction

PHP and PostgreSQL are a powerful combination when it comes to web development. PostgreSQL is an advanced open-source database system that provides developers with key scalability and replication functionalities, making it a frequent choice for complex data applications. Integrating PHP with PostgreSQL allows developers to create dynamic and robust web applications. This tutorial will guide you through the process of using PostgreSQL within a PHP environment.

Prerequisites

Before proceeding with this tutorial, you should have the following setup:

  • A working PHP environment (PHP 7.4 or later recommended).
  • PostgreSQL database installed and running.
  • Access to a terminal or command prompt.
  • Text editor or PHP integrated development environment (IDE).
  • Basic knowledge of PHP and SQL.

Installing PHP PostgreSQL Extensions

To interact with a PostgreSQL database using PHP, you must first ensure that your PHP installation has support for PostgreSQL. The PHP extensions for PostgreSQL are usually called ‘pgsql’ and ‘pdo_pgsql’. Here’s how you can install them:

On Ubuntu/Debian:

sudo apt-get update
sudo apt-get install php-pgsql

On CentOS/Red Hat:

sudo yum install php-pgsql

On Windows:

Uncomment the following lines in your php.ini file:

extension=php_pgsql.dll
extension=php_pdo_pgsql.dll

Restart your web server to apply the changes.

Once the extensions are enabled, you can start using PostgreSQL functions in your PHP scripts.

Establishing a Connection

Establishing a connection to your PostgreSQL database is the first step in executing queries. Use the pg_connect() function to create a connection:

$connection_string = "host=localhost dbname=mydb user=myuser password=mypass";
$dbconn = pg_connect($connection_string);

if (!$dbconn) {
    echo "Error: Unable to open database\n";
} else {
    echo "Opened database successfully\n";
}

Please replace 'localhost', 'mydb', 'myuser', and 'mypass' with your actual database host, database name, username, and password.

To use the PDO extension, you can open a connection as follows:

try {
    $dsn = "pgsql:host=localhost;port=5432;dbname=mydb;user=myuser;password=mypass";
    $db = new PDO($dsn);
    echo "Connected to database successfully";
} catch (PDOException $e) {
    echo $e->getMessage();
}

Executing Queries

With a valid database connection, you can now execute queries using PHP. Below is an example of executing a simple SELECT query using both procedural and object-oriented approaches:

Procedural:

$result = pg_query($dbconn, "SELECT id, name, email FROM users");

if (!$result) {
    echo "An error occurred.\n";
    exit;
}

while ($row = pg_fetch_assoc($result)) {
    echo "Id: " . $row['id'] . "\nName: " . $row['name'] . "\nEmail: " . $row['email'] . "\n";
}

PDO (Object-Oriented):

$stmt = $db->query("SELECT id, name, email FROM users");

while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    echo "Id: " . $row['id'] . "\n" .
         "Name: " . $row['name'] . "\n" .
         "Email: " . $row['email'] . "\n";
}

The query functions return a resource, which can be used with other pg_ functions (procedural) or they return a PDOStatement object which can be traversed using fetch methods (PDO).

Inserting Data

Inserting data into your database follows a similar pattern to querying data. Here’s an example:

$query = "INSERT INTO users (name, email) VALUES ('John Doe', '[email protected]')";
$result = pg_query($dbconn, $query);

if ($result) {
    echo "Record created successfully";
} else {
    echo "An error occurred.";
}

Using PDO with prepared statements not only makes it easier to insert dynamic data but also helps in preventing SQL injection:

$stmt = $db->prepare("INSERT INTO users (name, email) VALUES (:name, :email)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':email', $email);

// insert a row
$name = "Jane Doe";
$email = "[email protected]";
$stmt->execute();

echo "New records created successfully";

Handling Transactions

Transactions are important for maintaining the integrity of your data. Here’s a simplistic view of handling transactions with PDO:

try {
    // Begin a transaction
    $db->beginTransaction();

    // Insert records
    $db->exec("INSERT INTO users (name, email) VALUES ('Sam Smith', '[email protected]')");
    $db->exec("INSERT INTO products (name, quantity) VALUES ('Widget', 5)");

    // Commit the transaction
    $db->commit();
    echo "New records created successfully";
} catch (Exception $e) {
    // An error occurred; roll back the transaction
    $db->rollback();
    echo "Error: " . $e->getMessage();
}

This covers the basics of transactions, but it’s crucial to consider more complex scenarios requiring further logic and error handling in production applications.

Summary

This guide has covered the fundamental steps of working with PostgreSQL in PHP, including installing the necessary extensions, establishing a database connection, executing queries, inserting data, and handling transactions. By mastering these basics, you can build and interact with robust databases to support dynamic web applications.