Connecting to PostgreSQL via PHP

The following example shows how to connect to the PostgreSQL server via PHP.

Install PostgreSQL extension

The PostgreSQL extension is enabled by default in the latest releases of PHP 5.3.x.

If you are using a different version of PHP, you can use the command below to install PostgreSQL extension.

In CentOS:

yum install php-pgsql

In Ubuntu:

To install the latest version of the PostgreSQL extension.

sudo apt update
sudo apt install php-pgsql

To install a specific version of the PostgreSQL extension. Replace the {php version} with the version you'd like to install.

sudo apt update
sudo apt install php{php version}-pgsql

Connect to PostgreSQL Database

<?php

$host = 'postgresql-12***2-0.cloudclusters.net';
$port = '16**3';
$dbname = 'yourdbname';
$user = 'yourdbusername';
$password = 'yourdbpassword';


$dsn = "pgsql:host=$host;port=$port;dbname=$dbname;user=$user;password=$password";
try {
    $pdo = new PDO($dsn);
    echo "Connect to database sucessful";
} catch (PDOException $e) {
    echo "fail to connect to database" . $e->getMessage();
}
?>
Copyright © 2021 Cloud Clusters Inc. all right reserved,powered by GitbookRevised on 05/30/2023

results matching ""

    No results matching ""