All posts
PHPSeptember 4, 20267 min read

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.

F
Fepiq Team
Fepiq

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.

What you need before you start

  • PHP installed on your computer, version 7.4 or newer (check with php -v in your terminal).
  • PostgreSQL installed and running, with a database already created.
  • The PDO PostgreSQL driver enabled. Most PHP installations include it, but if pdo_pgsql is missing, you may need to install a package like php-pgsql.
  • Basic comfort with the command line and a text editor. You do not need to be a PHP or SQL expert.

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 PostgreSQL

Step 1: Know your connection details

To connect to any PostgreSQL database, you need four pieces of information. Write these down before you start coding.

DetailWhat it meansExample
HostThe address of the database serverlocalhost or 127.0.0.1
PortThe door PostgreSQL listens on5432 (the default)
Database nameThe specific database you want to usemy_app
Username and passwordThe account PostgreSQL uses to check accesspostgres / your_password

Step 2: Connect to PostgreSQL using PHP PDO

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
<?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.

Run it

bash
php db.php

If 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.

Step 3: Insert data into your PostgreSQL table

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
<?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.

Step 4: Fetch and display data from PostgreSQL

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
<?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.

PDO vs. the native pg_connect functions

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.

PDOpg_connect / pg_query
Works with other databases tooYes (MySQL, SQLite, and more)No, PostgreSQL only
Prepared statements supportYes, built inYes, but more manual
Beginner recommendationBest default choiceFine 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.

Common connection errors and how to fix them

  • "could not find driver" — the pdo_pgsql extension is not enabled. Enable it in your php.ini file and restart PHP.
  • "connection refused" — PostgreSQL is not running, or the host/port is wrong. Confirm PostgreSQL is started and listening on port 5432.
  • "password authentication failed" — the username or password is incorrect, or PostgreSQL's pg_hba.conf file is not allowing that login method.
  • "database does not exist" — check the spelling of your database name, or create the database first.

Frequently asked questions

Do I need to install anything extra to connect PHP to PostgreSQL?+

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.

What port does PostgreSQL use?+

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.

Is PDO better than pg_connect for PostgreSQL?+

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.

Why should I use prepared statements instead of writing the query directly?+

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.

Can I use this same code with a hosted PostgreSQL database?+

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 MySQL

You 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 Fepiq

Get new posts in your inbox

Occasional, no-fluff notes on shipping modern software — startups, automation, Laravel, Shopify and more. No spam, unsubscribe anytime.

Keep reading

Related posts

All posts

Let's build something

Ready to ship your next product with Fepiq?

Book a free discovery call. We'll listen, ask sharp questions, and send you a proposal within 3 business days.