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
Successfully made connection to PostgreSQL
In the preceding code, we used the pg_connect
function to make a connection to the database. If this function...