- Connect to a PostgreSQL Database using PHP and pg_connect
- Prerequisites
- A pgconnect example
- Connecting to PostgreSQL
- Prerequisites
- 1) PostgreSQL database parameters
- 2) Enable PostgreSQL driver
- PostgreSQL data source name
- Connecting to PostgreSQL
- Summary
- Connecting to PostgreSQL using PHP
- Installing PHP
- Connecting to the PostgreSQL server from PHP
- PHP command line Interface
- PHP API
Connect to a PostgreSQL Database using PHP and pg_connect
Returning data in a variety of forms to meet your needs is what can happen when you run a connect PostgreSQL database PHP pgconnect. It’s all up to you. For example, specifically, you can return a PostgreSQL database table into a table in HTML form. Use the pgconnect PHP method to connect to your database in PostgreSQL and save time displaying data in the way that you want.
If you’re already familiar with the steps of how to connect a PostgreSQL database with PHP using pgconnect, feel free to skip the details of this tutorial and go straight to Just the Code.
Prerequisites
- If you haven’t already, install PostgresSQL.
- Next, confirm the installation by opening a terminal window and inputting the command psql .
NOTE: Create a database and add some data to it so you can test the method call pgconnect using the examples in this tutorial.
- Check that on your Apache server, the latest ready PHP Version 7.x is running. Confirm the version in a terminal window like this:
- Be sure an Apache server localhost is active on your OS. To do this, open a browser tab 127.0.0.1 and verify that a response is returned.
- Use the cd command to log into your Apache server’s root directory.
- Construct a script in PHP. You’ll use it to make a database PostgreSQL connection.
NOTE: If you have a macOS and have trouble finding your Apache server’s root directory, check in its directory called /Library/WebServer/Documents .
- It’s important to confirm that PostgreSQL and the PHP library are configured correctly. To find out, copy and paste the code into the script when you edit it:
A pgconnect example
// it should return: “Warning: Wrong parameter count” if installed correctly echo pg_connect();
// show information about PHP and the packages installed phpinfo();
>__NOTE:__ Unless you’re using them for debugging, skip the code section representing `error_reporting` and `ini-set`. Those lines are for revealing web page errors.
* Open a tab in your browser and go to `http://localhost/postgres-test.php` after you saved the edited script with the code you copied. Inspect the web page. Reinstall PHP on your Apache server if the web page only shows the code of PHP.

### Addressing a fatal error response
You’ll need to install or reinstall libraries of PHP along with its packages if you receive the `Fatal error: Uncaught Error: Call to undefined function pg_connec()` response. These are necessary for using the method pgconnect.
* Apply the following sudo command to add the PHP PostgreSQL library and any required associations:
«`bash
sudo apt-get install php-pgsql
- For Unbuntu and Linux servers that are Debian-based, use the commands below to install additional dependencies.
sudo apt install apache2 apache2-utils
sudo apt install postgresql libpq5 postgresql- 9.5 postgresql-client- 9.5 postgresql-client-common postgresql-contrib
If you need to make configuration file edits, look in /etc/php/ for the .ini for PHP. A number indicating the version edition will be shown in the file name at the end of it (for example, /etc/php/7.3 or something similar to that).
Connecting to PostgreSQL
Summary: in this tutorial, you will learn how to connect to a PostgreSQL database server using PHP PDO.
Prerequisites
To make a connection to the PostgreSQL database server using PHP PDO, you need to have:
- A PostgreSQL database server, a database, and an account with a username and password that can access the database.
- PHP PDO PostgreSQL driver enabled in the php.ini file.
1) PostgreSQL database parameters
Suppose you have the following PostgreSQL database parameters:
- A PostgreSQL database server on the localhost .
- The dvdrental sample database.
- The account with the user postgres and password postgres that can access the dvdrental database on the local database server
The following creates a new database configuration file named config.php that stores the PostgreSQL database parameters:
$host= 'localhost'; $db = 'dvdrental'; $user = 'postgres'; $password = 'postgres'; // change to your password
Code language: HTML, XML (xml)
To use these parameters, you include the config.php file in the script that connects to the PostgreSQL using the require construct.
2) Enable PostgreSQL driver
The PDO_PGSQL is a driver that implements the PDO interface. It allows you to access PostgreSQL databases from PHP.
To check if the PDO_PGSQL driver is enabled, you open the php.ini file. Typically, the php.ini file is located under the php directory. For example, if you use XAMPP on Windows, you can find the php.ini file under the C:\xampp\php directory.
in the php.ini file, you can find the following line:
;extension=php_pdo_pgsql.dll
If you see the comma( ; ) placed at the beginning of the line, it means that the line is commented and the database driver is not enabled.
To enable the driver, you need to uncomment the line by removing the comma ( ; ) like this:
extension=php_pdo_pgsql.dll
After that, you need to restart the web server to apply the change.
PostgreSQL data source name
The data source name or DSN holds database parameters that enable access to a database system. The data source name of the PostgreSQL consists of the following parameters:
- pgsql: is the DNS prefix.
- host: the host of the server where the PostgreSQL runs.
- port: the port to which PostgreSQL listens. The default PostgreSQL’s port is 5432 .
- dbname: the database name that you want to connect to.
- And other parameters.
The following shows a DSN that connects to dvdrental database in the local PostgreSQL Server, port 5432:
pgsql:host=localhost;port=5432;dbname=dvdrental;
Connecting to PostgreSQL
The following illustrates how to connect to the dvdrental database in PostgreSQL database server:
require_once 'config.php'; try < $dsn = "pgsql:host=$host;port=5432;dbname=$db;"; // make a database connection $pdo = new PDO($dsn, $user, $password, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]); if ($pdo) < echo "Connected to the $db database successfully!"; > > catch (PDOException $e) < die($e->getMessage()); > finally < if ($pdo) < $pdo = null; > >
Code language: HTML, XML (xml)
- First, make a new connection to the PostgreSQL database by creating a new instance of the PDO class.
- Second, show a message if the database connection is established successfully; otherwise, show an error message.
The following option instruct PDO to set an error code and throw an exception if an error occurs:
[PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
Code language: PHP (php)
PDO has three exception handling options:
- PDO::ERROR_SILENT – PDO sets an error code for inspecting using the PDO::errorCode() and PDO::errorInfo() methods. The PDO::ERROR_SILENT is the default mode.
- PDO::ERRMODE_WARNING – Besides setting the error code, PDO will issue an E_WARNING message.
- PDO::ERRMODE_EXCEPTION – Besides setting the error code, PDO will raise a PDOException .
Note that PHP automatically closes the database connection when the script ends. If you want to close the database connection explicitly, you can set the PDO instance to null:
$pdo = null;
Code language: HTML, XML (xml)
The following connect.php script defines a connect() function that makes a connection to the PostgreSQL database and returns an instance of the PDO class:
require_once 'config.php'; function connect(string $host, string $db, string $user, string $password): PDO < try < $dsn = "pgsql:host=$host;port=5432;dbname=$db;"; // make a database connection return new PDO( $dsn, $user, $password, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION] ); > catch (PDOException $e) < die($e->getMessage()); > > return connect($host, $db, $user, $password);
Code language: HTML, XML (xml)
To use this connect.php in a script, you use the require construct as follows:
$pdo = require 'connect.php'; // start working with the database
Code language: HTML, XML (xml)
Summary
- Enable PostgreSQL extension in php.ini file by removing the semicolon ( ; ) from the line extension=php_pdo_pgsql.dll
- Create a new instance of PDO by passing the data source name (DSN) to its constructor to make a connection to the PostgreSQL database server.
Connecting to PostgreSQL using PHP
SUMMARY: This article reviews the steps necessary for connecting to a PostgreSQL database using PHP.
2. Connecting to the PostgreSQL from PHP
a. PHP command line interface
Note: although the steps in this post refer to the EnterpriseDB Advanced server, the same steps work for PostgreSQL community version as well.
Installing PHP
Before you can begin developing PHP scripts that interact with a PostgreSQL database, first you need to confirm if PHP is installed on your machine, and second you will need to confirm PostgreSQL support in your PHP installation.
To confirm if PHP is installed on your Linux machine, you can use the following command:
[root@kubemaster ~]# rpm -qa | grep php Php-json-7.3.11-1.el7.remi.x86_64 php-opcache-7.3.11-1.el7.remi.x86_64 php-common-7.3.11-1.el7.remi.x86_64 php-gd-7.3.11-1.el7.remi.x86_64 php-pdo-7.3.11-1.el7.remi.x86_64 php-mysqlnd-7.3.11-1.el7.remi.x86_64 php-pecl-mcrypt-1.0.3-1.el7.remi.7.3.x86_64 php-7.3.11-1.el7.remi.x86_64 Php-cli-7.3.11-1.el7.remi.x86_64
If PHP is not installed, then you can refer to the PHP installation instructions available here: https://www.linuxtechi.com/install-php-7-centos-7-rhel-7-server/
If you’re not sure whether your existing PHP installation already has PostgreSQL support, create a simple script named phpinfo.php (which should be placed in your web server’s document root, i.e., /var/www/html/), containing the following line:
Check the output of this script in your web browser. If PostgreSQL support has already been included, the output will contain a section similar to the following:
Note: In this document “web server” refers to an Apache web server whose document root is /var/www/html.
Connecting to the PostgreSQL server from PHP
All interactions with the PostgreSQL database are performed through the PostgreSQL extension, which is a comprehensive set of PHP functions. For a complete list of functions and information about what they do, refer to the PHP Manual instructions: http://www.php.net/manual/ref.pgsql.php.
There are two ways we can connect to the PostgreSQL database:
- Using the PHP command line interface.
- Using PHP API.
PHP command line Interface
Using the functions below we can connect to the PostgreSQL database:
[root@localhost bin]#cd /usr/bin/ [root@localhost bin]# ./php -a
php > pg_connect("host=localhost dbname=edb user=enterprisedb password=postgres"); php > pg_query("create table test(id integer)"); php > exit
edb=# \dt List of relations Schema | Name | Type | Owner --------+------+-------+-------------- public | test | table | enterprisedb (1 row) edb=# \d+ test Table "public.test" Column | Type | Collation | Nullable | Default | Storage | Stats target | Description --------+---------+-----------+----------+---------+---------+--------------+------------- id | integer | | | | plain | |
PHP API
A simple PHP script that opens a connection to a PostgreSQL database, create a table would look something like this:
[root@localhost bin]#cd /var/www/html [root@localhost bin]#cd /var/www/html [root@localhost bin]#vi test.phpThe above test.php file needs to be executed from the browser at http://localhost/test.php:
As you can see, interacting with the database from within PHP is fairly straightforward using pg_connect(). If the connection attempt fails, the pg_connect() function will return false. Failed connection attempts can, thus, be detected by testing the return value:
[root@localhost bin]#cd /var/www/html [root@localhost bin]#vi connection.php else < echo 'Connection attempt failed.'; >pg_close($db_handle); ?>
Execute the connection.php script from the browser at http://localhost/connection.php:
The PHP script below is a single script you can use to perform PHP connection testing, query status checking, and data fetching from the database.
======================================== [root@localhost bin]#cd /var/www/html [root@localhost bin]#vi connection_test.php else < echo 'Connection attempt failed.'; >echo "Connection Information
"; echo "DATABASE NAME:" . pg_dbname($db_handle) . "
"; echo "HOSTNAME: " . pg_host($db_handle) . "
"; echo "PORT: " . pg_port($db_handle) . "
"; echo "Checking the query status
"; $query = "SELECT fname,lname FROM person"; $result = pg_exec($db_handle, $query); if ($result) < echo "The query executed successfully.
"; echo "Print First and last name:
"; for ($row = 0; $row < pg_numrows($result); $row++) < $firstname = pg_result($result, $row, 'fname'); echo $firstname ." "; $lastname = pg_result($result, $row, 'lname'); echo $lastname ."
"; > > else < echo "The query failed with the following error:
"; echo pg_errormessage($db_handle); > pg_close($db_handle); ?>