# Connecting with PHP

This guide explains how to establish a connection between a **PHP** application and a **PostgreSQL** database using the built-in `PDO` extension. It walks through the necessary setup, configuration, and execution of a simple SQL query.

### **Variables**

To connect to a PostgreSQL database, you only need one environment variable — the **connection URI**. This URI contains all the necessary information like username, password, host, port, and database name.

<div class="overflow-x-auto contain-inline-size" id="bkmrk-variable-description"><table border="1" data-end="1005" data-start="750" style="border-collapse: collapse; border-color: rgb(0, 0, 0);"><thead data-end="786" data-start="750"><tr data-end="786" data-start="750"><th data-end="761" data-start="750" style="border-color: rgb(0, 0, 0);">Variable</th><th data-end="775" data-start="761" style="border-color: rgb(0, 0, 0);">Description</th><th data-end="786" data-start="775" style="border-color: rgb(0, 0, 0);">Purpose</th></tr></thead><tbody data-end="1005" data-start="824"><tr data-end="1005" data-start="824"><td style="border-color: rgb(0, 0, 0);">**POSTGRESQL\_URI**</td><td style="border-color: rgb(0, 0, 0);">Full PostgreSQL connection string (from the Elestio service overview page)</td><td style="border-color: rgb(0, 0, 0);">Provides all necessary credentials and endpoint details in a single URI format.</td></tr></tbody></table>

</div>The URI will look like this:

```bash
postgresql://<USER>:<PASSWORD>@<HOST>:<PORT>/<DATABASE>
```

You can find the details needed in the URI from the **Elestio service overview** details. Copy and replace the variables carefully in the URI example provided above.

![image.png](https://docs.elest.io/uploads/images/gallery/2025-03/scaled-1680-/ZvEimage.png)

### **Prerequisites**

##### **Install PHP**

Check if PHP is installed by running:

```bash
php -v
```

If not installed, download and install it from [https://www.php.net/downloads.php](https://www.php.net/downloads.php).

### **Code**

Once all prerequisites are set up, create a new file named `pg.php` and add the following code and replace the `POSTGRESQL_URI` with actual link or in environment setup as you wish:

```php
<?php

$db_url = "POSTGRESQL_URI";//Replace with actual URI
$db_parts = parse_url($db_url);

$dsn = "pgsql:host={$db_parts['host']};port={$db_parts['port']};dbname=Elestio";//Replace with your DB name
$pdo = new PDO($dsn, $db_parts['user'], $db_parts['pass']);

$version = $pdo->query("SELECT VERSION()")->fetchColumn();
echo $version;
```

To execute the script, open the terminal or command prompt and navigate to the directory where `pg.php`. Once in the correct directory, run the script with the command

```kotlin
php pg.php
```

If the connection is successful, the terminal will display output similar to:

```bash
PostgreSQL 16.8 (Debian 16.8-1.pgdg120+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 12.2.0-14) 12.2.0, 64-bit
```