Connecting to PostgreSQL using PHP

January 24, 2023

SUMMARY: This article reviews the steps necessary for connecting to a PostgreSQL database using PHP.

 

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:

<?php  

phpinfo();

  ?>

 

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:

  1. Using the PHP command line interface.
     
  2. 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

 

Interactive shell:

php > pg_connect("host=localhost dbname=edb user=enterprisedb password=postgres");

php > pg_query("create table test(id integer)");

php > exit

 

Output from the database:

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.php

<!DOCTYPE html>

<html>

<body>

<?php

echo "My first PHP script!";

pg_connect("host=localhost dbname=edb user=enterprisedb password=postgres");

pg_query("create table testing(id integer)");

echo " script! Executed";

?>

</body>

</html>

 

The 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

<?php

$db_handle = pg_connect("host=localhost dbname=edb user=enterprisedb password=postgres");

if ($db_handle) {

echo 'Connection attempt succeeded.';

} 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

<?php

$db_handle = pg_connect("host=localhost dbname=edb user=enterprisedb password=postgres");

if ($db_handle) {

echo 'Connection attempt succeeded.';

} else {

   

echo 'Connection attempt failed.';

}

echo "<h3>Connection Information</h3>";

echo "DATABASE NAME:" . pg_dbname($db_handle) . "<br>";

echo "HOSTNAME: " . pg_host($db_handle) . "<br>";

echo "PORT: " . pg_port($db_handle) . "<br>";

echo "<h3>Checking the query status</h3>";

$query = "SELECT fname,lname FROM person";

$result = pg_exec($db_handle, $query);

if ($result) {

echo "The query executed successfully.<br>";

echo "<h3>Print First and last name:</h3>";

for ($row = 0; $row < pg_numrows($result); $row++) {

$firstname = pg_result($result, $row, 'fname');

echo $firstname ." ";

$lastname = pg_result($result, $row, 'lname');

echo $lastname ."<br>";

}

} else {

echo "The query failed with the following error:<br>";

echo pg_errormessage($db_handle);

}

pg_close($db_handle);

?>

 

Execute the connection_test.php script from the browser at http://localhost/connection_test.php:

 

Share this

More Blogs