How to connect postgresql database in php

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

1. Installing PHP

2. Connecting to the PostgreSQL from PHP

       a. PHP command line interface

       b. PHP API

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:

How to connect postgresql database in php

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











The above test.php file needs to be executed from the browser at http://localhost/test.php:

How to connect postgresql database in 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

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

How to connect postgresql database in 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

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); ?>

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

How to connect postgresql database in php

Can PHP work with PostgreSQL?

PHP provides many functions for working directly with PostgreSQL databases. To connect to PostgreSQL using native functions, follow these steps: Use the following PHP code to connect to PostgreSQL and select a database.

How do I connect my postgres database to my website?

Connect to a PostgreSQL Database Server.
Step1: Launch the pgAdmin application. ... .
Step2: Create a server. ... .
Step3: Provide the server name. ... .
Step4: Provide the host and password. ... .
Step5: Expanding the server. ... .
Step6: Open the Query tool. ... .
Step7: Enter the command in the Query editor. ... .
Step1: Open the psql..

What is PostgreSQL in PHP?

Connect to PostgreSQL using PDO (PHP Data Objects) As of version 5.1 PHP provides new database connection abstraction library, PHP Data Objects or PDO. PDO abstracts database access, and enables you to use code that can handle different types of databases.

What is the PHP provided function that is called to connect to a PostgreSQL database?

pg_connect() opens a connection to a PostgreSQL database specified by the connection_string .