# Connecting to PostgreSQL using PHP

> Connect a PHP script to a PostgreSQL database using the native pg functions or PDO, with code examples for each.

Source: https://helpcenter.ruachost.com/developers/databases/connecting-to-postgresql-using-php/

> **PostgreSQL is available on Managed VPS only:**
Ruachost shared hosting supports MySQL (MariaDB) databases, not PostgreSQL. To use PostgreSQL, choose a [Managed VPS](https://ruachost.com/vps).

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.

## Why Connect with PHP?

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

## Methods to Connect to PostgreSQL

### 1. Using Native PostgreSQL Functions

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

### Example

```
<?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>";
}
?>
```

### 2. Using PDO (PHP Data Objects)

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

### Example

```
<?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();
}
?>
```

> **Important Notes:**
- Replace `localhost`, `yourdbname`, `yourusername`, and `yourpassword` with your actual database credentials.
- Ensure PostgreSQL and PHP extensions (`pgsql` or `pdo_pgsql`) are enabled on your hosting account.
- Always handle errors gracefully to avoid exposing sensitive information.
- Use prepared statements in PDO for secure queries against SQL injection.
