Skip to content

Connecting to PostgreSQL using PHP

PHP provides built‑in functions and PDO (PHP Data Objects) for connecting to PostgreSQL databases. On ruachost.com, you can use either method depending on your project requirements.

  • Enables dynamic web applications to interact with PostgreSQL.
  • Allows you to run queries, insert/update records, and fetch data.
  • PDO provides flexibility to switch between different database systems with minimal code changes.

PHP includes native functions such as pg_connect() and pg_query().

<?php
// Connect to PostgreSQL
$db_connection = pg_connect("host=localhost dbname=yourdbname user=yourusername password=yourpassword");
// Run a query
$result = pg_query($db_connection, "SELECT lastname FROM employees");
// Fetch results
while ($row = pg_fetch_assoc($result)) {
echo $row['lastname'] . "<br>";
}
?>

PDO abstracts database access, making it easier to switch between different database engines.

<?php
try {
// Connect to PostgreSQL using PDO
$pdo = new PDO("pgsql:host=localhost;dbname=yourdbname", "yourusername", "yourpassword");
// Run a query
$stmt = $pdo->query("SELECT lastname FROM employees");
// Fetch results
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo $row['lastname'] . "<br>";
}
} catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>