How Do You Connect to a Specific Database in Postgres Using PHP?

Problem scenario
Using PHP you want to connect to a specific database to run SQL queries.  How do you do this?

Assuming you have installed PHP and Postgres on the same Ubuntu Linux server, install the php-pgsql package.  Follow this link if you need assistance.  

1.  Create a file like this named contint.php:

   $host        = "host=";
   $port        = "port=5432";
   $dbname      = "dbname=contintdb";
   $credentials = 'user=jdoe password=abcd1234';

   $db = pg_connect( "$host $port $dbname $credentials"  );

   pg_query("insert into contintTable values(511);");

2.  Change the $dbname variable assignment in the code below.  This is how you specify a database. You will need to change the credentials and the pg_query code too. Change the IP address if the Postgres server is on a different server from the server with PHP.

​3.  Run it with this command: php contint.php

Leave a comment

Your email address will not be published. Required fields are marked *