Skip to content
PHP Logo

What are the common methods for accessing a PostgreSQL database with PHP?

When accessing a PostgreSQL database with PHP, the most common methods include using the PDO (PHP Data Objects) extension or the pgsql extension. PDO provides a consistent interface for accessing various databases, including PostgreSQL, while the pgsql extension is specific to PostgreSQL. Both extensions allow you to connect to a PostgreSQL database, execute queries, and fetch results in your PHP code.

php
// Using PDO extension to connect to a PostgreSQL database
$host = 'localhost';
$dbname = 'mydatabase';
$username = 'myuser';
$password = 'mypassword';

try {
    $pdo = new PDO("pgsql:host=$host;dbname=$dbname", $username, $password);
    echo 'Connected to the database';
} catch (PDOException $e) {
    die("Error: Could not connect to the database - " . $e->getMessage());
}