How to Use PostgreSQL PDO Driver with PHP Part 1

Introduction

This tutorial will explain how to connect PHP to PostgreSQL with the PDO driver and create the PHP project structure with Composer, a dependency-management tool in PHP. Compose allows for verifying the libraries a project requires and it will install and update the libraries as needed. Be sure all the prerequisites are properly in place before beginning the exercises in this tutorial.

Prerequisites to Connect PHP to PostgreSQL with the PDO Driver.

  • PHP must be properly installed and configured. Check for the current PHP installation version by executing the php -v command. The result should look something like the following in the Linux system:
PHP 7.3.7-2+ubuntu18.04.1+deb.sury.org+1 (cli) (built: Jul 25 2019 11:44:59) ( NTS )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.3.7, Copyright (c) 1998-2018 Zend Technologies
with Zend OPcache v7.3.7-2+ubuntu18.04.1+deb.sury.org+1, Copyright (c) 1999-2018, by Zend Technologies

The result should resemble the following in a Windows system:


GeSHi Error: GeSHi could not find the language ps (using path /nas/content/live/orkbprod/wp-content/plugins/codecolorer/lib/geshi/) (code 2)
  • The PostgreSQL server must be properly installed, configured and running in the background.

Execute the following command to start the PostgreSQL server:

sudo service postgresql start

Now execute the following command to verify the service is running:

service postgresql status

The result should resemble the following:

â— postgresql.service - PostgreSQL RDBMS
Loaded: loaded (/lib/systemd/system/postgresql.service; enabled; vendor prese
Active: active (exited) since Thu 2019-08-01 14:51:20 PST; 36min ago
Process: 1230 ExecStart=/bin/true (code=exited, status=0/SUCCESS)
Main PID: 1230 (code=exited, status=0/SUCCESS)

Aug 01 14:51:20 user-UX330UAK systemd[1]: Starting PostgreSQL RDBMS...
Aug 01 14:51:20 user-UX330UAK systemd[1]: Started PostgreSQL RDBMS.
lines 1-8/8 (END)
  • Composer must be properly installed and configured. Entering the composer –version command should return the following results:
Composer 1.6.3 2018-01-31 16:28:17

PDO and PHP Data Objects

The PHP data objects, or PDO, defines a lightweight, unified interface for accessing the relational databases, or RDB, in PHP. Each database defines the driver specific to that database that implements the PDO interface. Each driver can also reveal the database-specific functions as a normal extension of the functions.

NOTE: Most PHP distributions includes PostgreSQL extension PDO_PGSQL by default. However, the extension can be edited in the php.ini file. Just remove the prefixed semicolon (;) to uncomment the following line with ;extension=php_pdo_pgsql.dll.

How to Create the PHP Project Structure with Composer

This section will explain how to use Composer to create the project-directory structure.

  1. Create a folder and name it something meaningful, in this case the folder will be named for the project directory as “postgreSQL_php”.

  2. Create a sub-folder and name it “control.” Then create a json file named composer.json and put the following json script inside the control file:


GeSHi Error: GeSHi could not find the language json (using path /nas/content/live/orkbprod/wp-content/plugins/codecolorer/lib/geshi/) (code 2)

The above script handles the mapping of every class that will be created and added to the PostgreSQL namespace.

NOTE: The PHP Standard Recommendations isPSR-4: Improved Autoloading for using FQCN in a file path.

  1. Navigate to the project directory via the terminal then execute the below command. Note that in this case the system project directory is located at “var/www/html/postgreSQL_php”.
composer update

The above Composer command will download the declared libraries within the composer.json file and will generate an autoload file. Composer will also create a folder named vendor and insert all of the third-party libraries in it. However, in this case no third-party library was specified so composer will only generate the autoload file. The results should resemble the following.

Loading composer repositories with package information
Updating dependencies (including require-dev)
Nothing to install or update
Generating autoload files
  1. Create a PHP file named index.PHP in the root project directory using the following touch command:
touch index.php
  1. Create two additional files within the control folder named connection.php and config.ini and then repeat the same process used in the previous section in sequence.

First execute:

touch connection.php

Then execute:

touch config.ini

To verify the following file was created, use the ls command. The results should resemble the following:

bash/var/www/html/postgreSQL_php/control $ ls
config.ini connection.php

How to Create a PostgreSQL Database

Execute the following command in the terminal to create a database where the connection can be tested later:

sudo -u postgres psql createdb testDatabase

Execute the following command, in sequence, to verify the database was successfully created:

sudo -i -u postgres

then

l

The result should resemble the following:

List of databases
Name | Owner | Encoding | Collate | Ctype | Access privileges
--------------+----------+----------+-------------+-------------+-----------------------
postgres | postgres | UTF8 | en_PH.UTF-8 | en_PH.UTF-8 |
template0 | postgres | UTF8 | en_PH.UTF-8 | en_PH.UTF-8 | =c/postgres +
| | | | | postgres=CTc/postgres
template1 | postgres | UTF8 | en_PH.UTF-8 | en_PH.UTF-8 | =c/postgres +
| | | | | postgres=CTc/postgres
testDatabase | postgres | UTF8 | en_PH.UTF-8 | en_PH.UTF-8 |
(4 rows)

The above are the results for the database testDatabase.

How to Connect PHP to the PostgreSQL Database

With the project and the database properly set up, add functionalities to the files that were created in the previous section.

The Configuration for config.ini

Open the config.ini using the nano editor and add the following configuration by executing the following command:

sudo nano /var/www/html/postgreaSQL_php/control/config.ini

Now add the following PostgreSQL database parameters:


GeSHi Error: GeSHi could not find the language txt (using path /nas/content/live/orkbprod/wp-content/plugins/codecolorer/lib/geshi/) (code 2)

How to create the PHP code for the connection.php

Now create a PHP class named Connection inside the connection.php file with the same process used in the previous section. However, this time edit the connection.php file using nano with the following commands:

sudo nano /var/www/html/postgreSQL_php/control/connection.php

Now add the following PHP script in the connection.php:

<?php
namespace PostgreSQLPHP;


/**
* Represents the Connection
*/

class Connection {

/**
* The Connection
* @var type
*/

private static $conn;

/**
* Connect to the database and return an instance of PDO object
* @return PDO
* @throws Exception
*/

public function connect() {

// The following script will parse the parameters in the config.ini configuration file
$params = parse_ini_file('config.ini');
if ($params === false) {
throw new Exception("Error reading database configuration file");
}
// connect to the postgresql database from the config.file parameters
$conStr = sprintf("pgsql:host=%s;dbname=%s;user=%s;password=%s",
$params['host'],
$params['database'],
$params['user'],
$params['password']);

$pdo = new PDO($conStr);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

return $pdo;
}

/**
* return an instance of the Connection object
* @return type
*/

public static function get() {
if (null === static::$conn) {
static::$conn = new static();
}

return static::$conn;
}


}

The above code is a bit lengthy. Here is a breakdown:

  1. A singleton class Connection class was used. This will create only one instance and if an instance already exists while trying to create a new one, the class returns the reference to the old instance.

  2. Before connecting to a PostgreSQL database a new PDO instance class must be created.

The PHP code for the index.php

Below is the PHP script of the index.php file:

<?php
require 'vendor/autoload.php';

use PostgreSQLPHPConnection as Connection;

try {
Connection::get()->connect();
echo 'PostgreSQL Server : database connection has been established successfully.';
} catch (PDOException $e) {
echo $e->getMessage();
}
?>

The above code will catch a PDOException, if one should occur when connecting to the PostgreSQL database server.

With the connection setup, now update the autoload files using the following command:

composer dump-autoload -o

NOTE: Be sure to be in the project root directory when executing the above command.

The result should be: Generating optimized autoload files.

How to Test the PostgreSQL Connection with PHP

With the PHP scripts and configuration set up, test the new program using the built-in Webserver, however, this feature is only available in PHP versions 5.4 and above. Navigate to the project directory and run the following command:

PHP -S localhost:9090

The results should resemble the following:

Listening on http://localhost:9090
Document root is /var/www/html/postgreSQL_php
Press Ctrl-C to quit.

Navigate to the browser and type in localhost:9090.

The results should resemble the following:

PostgreSQL Server : database connection has been established successfully.

Conclusion

This tutorial covered how to connect PHP to PostgreSQL with the PDO driver. The article explained PDO and PHP data objects and how to create the PHP project structure with Composer. The tutorial also covered how to create a PostgreSQL database, how to connect PHP to the PostgreSQL database, how to create the PHP code, a breakdown of the code and how to test the PostgreSQL connection with PHP. Remember that testing the PostgreSQL connection using the built-in Webserver can only be done in PHP versions 5.4 and above.

Pilot the ObjectRocket platform free for 30 Days

It's easy to get started. Imagine the time you'll save by not worrying about database management. Let's do this!

PILOT FREE FOR 30 DAYS

Keep in the know!

Subscribe to our emails and we’ll let you know what’s going on at ObjectRocket. We hate spam and make it easy to unsubscribe.