Skip to main content

Connecting with PHP

This guide explains how to connect a PHP application to a TimescaleDB database using the PDO extension. It covers setting up prerequisites, configuring the connection URI, and running a test SQL query.

Variables

To connect to a TimescaleDB database, you only need one environment variable — the connection URI.

Variable

Description

Purpose

TIMESCALE_URI

Full TimescaleDB connection string from Elestio

Encodes all connection info in one URI

A typical URI looks like this:

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.

Screenshot 2025-05-13 at 12.30.16 PM.jpg

Prerequisites

Install PHP

Check if PHP is installed:

php -v

If not, download and install PHP from: https://www.php.net/downloads.php

Code

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

<?php
$db_url = getenv("TIMESCALE_URI") ?: "postgresql://user:password@host:port/database";
$db_parts = parse_url($db_url);
$db_name = ltrim($db_parts['path'], '/');
$dsn = "pgsql:host={$db_parts['host']};port={$db_parts['port']};dbname={$db_name}";

try {
    $pdo = new PDO($dsn, $db_parts['user'], $db_parts['pass']);
    $version = $pdo->query("SELECT VERSION()")->fetchColumn();
    echo "Connected to TimescaleDB: " . $version . PHP_EOL;
} catch (PDOException $e) {
    echo "Connection failed: " . $e->getMessage() . PHP_EOL;
}

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

export TIMESCALE_URI=postgresql://user:password@host:port/database

Navigate to the directory containing tdb.php and run:

php tdb.php

If successful, you’ll see output like: