How to Connect PHP to a PostgreSQL Database (Guide)
Learn how to connect PHP to a PostgreSQL database step by step, using PDO, with beginner-friendly code examples for inserting and reading data.
Learn how to connect PHP to a PostgreSQL database step by step, using PDO, with beginner-friendly code examples for inserting and reading data.
If you searched for how to connect PHP to a PostgreSQL database, here is the short answer: you use PHP's built-in PDO (PHP Data Objects) extension to open a connection with a database name, username, and password, then use that connection object to run SQL queries. This guide walks through every step with small, copy-pasteable code examples, so you can follow along even if you have never connected PHP to a database before.
PostgreSQL (often called "Postgres") is a free, open-source database. PHP is a popular language for building websites. Together, they let you build a site that saves and reads data, like a list of users, blog posts, or orders.
Not sure how to create your first PostgreSQL table? Start with our beginner guide on creating tables, then come back here to connect PHP to it.
New to PostgreSQL? Learn how to create your first table before connecting PHP to it.
Read: How to Create a Table in PostgreSQLTo connect to any PostgreSQL database, you need four pieces of information. Write these down before you start coding.
| Detail | What it means | Example |
|---|---|---|
| Host | The address of the database server | localhost or 127.0.0.1 |
| Port | The door PostgreSQL listens on | 5432 (the default) |
| Database name | The specific database you want to use | my_app |
| Username and password | The account PostgreSQL uses to check access | postgres / your_password |
PDO is the recommended way to talk to a database from PHP. It works the same way for PostgreSQL, MySQL, and other databases, so the skills you learn here carry over. Create a new file called db.php and add this code:
<?php
$host = "localhost";
$port = "5432";
$dbname = "my_app";
$user = "postgres";
$password = "your_password";
$dsn = "pgsql:host=$host;port=$port;dbname=$dbname";
try {
$pdo = new PDO($dsn, $user, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected to PostgreSQL successfully!";
} catch (PDOException $e) {
die("Connection failed: " . $e->getMessage());
}Here is what each part does. $dsn stands for "Data Source Name" — it is a single string that tells PDO which database driver to use (pgsql) and where to find the database. new PDO($dsn, $user, $password) opens the actual connection and stores it in the $pdo variable. setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION) tells PDO to throw an error you can catch, instead of failing silently. The try/catch block runs your connection code, and if anything goes wrong, it prints a clear error message instead of crashing with a confusing PHP warning.
php db.phpIf you see "Connected to PostgreSQL successfully!", your PHP script can talk to your database. If you see "Connection failed", double-check your host, port, database name, username, and password.
Once you are connected, you can save data. Imagine you have a table called users with columns id, name, and email. Here is how to insert a new row safely:
<?php
require "db.php";
$name = "Ada Lovelace";
$email = "ada@example.com";
$sql = "INSERT INTO users (name, email) VALUES (:name, :email)";
$stmt = $pdo->prepare($sql);
$stmt->execute([
"name" => $name,
"email" => $email
]);
echo "New user added!";require "db.php" reuses the connection code from Step 2, so $pdo is already available. Notice the query uses :name and :email instead of the raw variables — these are called placeholders. $pdo->prepare() builds the query without filling in the values yet, and $stmt->execute() safely fills them in afterward. This pattern is called a prepared statement, and it protects your app from SQL injection, a common attack where malicious text is typed into a form to trick your database into running unwanted commands. Always use placeholders instead of pasting user input directly into a SQL string.
Now let's read the data back out and print it. This is the same pattern you would use to list users on a webpage.
<?php
require "db.php";
$sql = "SELECT id, name, email FROM users ORDER BY id";
$stmt = $pdo->query($sql);
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo $row["id"] . ": " . $row["name"] . " (" . $row["email"] . ")\n";
}$pdo->query() runs a SELECT statement that has no user input, so it is safe to run directly (use prepare() instead whenever a query includes a variable). $stmt->fetch(PDO::FETCH_ASSOC) pulls back one row at a time as an associative array, meaning you can access columns by name, like $row["name"]. The while loop keeps calling fetch() until there are no more rows, printing each user as it goes.
You may also see PHP code that uses pg_connect() and pg_query() instead of PDO. Both can connect PHP to PostgreSQL, but they are not the same.
| PDO | pg_connect / pg_query | |
|---|---|---|
| Works with other databases too | Yes (MySQL, SQLite, and more) | No, PostgreSQL only |
| Prepared statements support | Yes, built in | Yes, but more manual |
| Beginner recommendation | Best default choice | Fine for PostgreSQL-only scripts |
For beginners, stick with PDO. It is the more widely used approach, and if you ever switch databases later, most of your code stays the same.
You need the pdo_pgsql PHP extension enabled. Many PHP installations already include it. You can check by running php -m and looking for pdo_pgsql in the list; if it is missing, install a package like php-pgsql and restart your web server.
PostgreSQL uses port 5432 by default. You only need to change this if your server was set up with a custom port, which your database administrator or hosting provider can confirm.
For most beginners, yes. PDO gives you built-in prepared statements and works the same way across different databases, which makes your code easier to reuse. pg_connect still works, but it is PostgreSQL-specific and less commonly recommended today.
Prepared statements keep user input separate from your SQL command, which prevents SQL injection attacks. Even for a simple beginner project, it is a good habit to build early so it becomes automatic.
Yes. The PHP code stays the same — you only change the host, port, database name, username, and password in the connection details to match the ones your hosting provider gives you.
Want to compare this with connecting PHP to MySQL instead? Read our beginner guide on connecting PHP to a MySQL database.
Read: Connect PHP to MySQLYou now know how to connect PHP to PostgreSQL, insert data safely, and fetch it back out. From here, try building a simple form that saves data using the insert code above, then a page that lists it using the fetch code. That small project covers most of what a real web app needs to talk to its database.
Need help building a PHP and PostgreSQL app for your business?
Talk to FepiqOccasional, no-fluff notes on shipping modern software — startups, automation, Laravel, Shopify and more. No spam, unsubscribe anytime.
Keep reading
What is an index in SQL? A plain-English guide with copy-paste examples showing how indexes speed up queries and when you actually need one.
Learn JavaScript DOM manipulation for beginners: select elements, change text and styles, and handle clicks with simple, copy-paste code examples.
Let's build something
Book a free discovery call. We'll listen, ask sharp questions, and send you a proposal within 3 business days.