PHP-to-PostgreSQL connections

To make a connection to PostgreSQL from PHP, we have a set of built-in functions where we need to pass our connection string and a set of client options to make a connection. Here, we have the pg_connect() and pg_pconnect() functions in PHP that will get the connection from PostgreSQL.

Now, let's try a simple connection to Postgres using PHP:

<?php 
$dbcon = pg_connect("host=localhost port=5432 dbname=postgres user=postgres"); 
 
if (!$dbcon) { 
  echo"Unable to make connection"; 
  exit; 
} 
else { 
  echo"Successfully made connection to PostgreSQL\n"; 
} 
?> 

To run the PHP code, we need to either embed the code in an HTML file and then call the web page or we can use the PHP command-line interface.

The result is as follows:

$ php /tmp/test.php ...

Get PostgreSQL Development Essentials now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.