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        = "host = postgresql-xxxx-0.tripanels.com";
   $port        = "port = 40xx";
   $dbname      = "dbname = testdatabase";
   $credentials = "user = testuser password=Testuser123go";

   $db = pg_connect( "$host $port $dbname $credentials"  );
   if(!$db) {
      echo "Error : Unable to open database\n";
   } else {
      echo "Opened database successfully\n";
   }
?>
Copyright © 2021 Cloud Clusters Inc. all right reserved,powered by GitbookRevised on 09/30/2021

results matching ""

    No results matching ""