Testing Postgres connection with PHP in Ubuntu

Default featured post

PHP is very powerful programming language to write different web application and that is the one of the most important reason I choose to learn it alongside with Python. However, database connection is getting troublesome in PHP specially for new programmers like me even though PHP is quite straightforward and easy to learn. Therefore, the problem might cause a lot of headache and makes debugging process though.

In order to make things easier and smoother, I have decided to write a simple PHP script to make connection to PostgreSQL database to test whether can make connection to db or not and make troubleshooting faster and easier. So here is my script.

First of copy/paste the below code and save it as db_connection.php and open and configure it accordingly.

   $host        = "host=";
   $port        = "port=5432";
   $dbname      = "dbname=test123";
   $credentials = "user=kasra password=001";
   $db = pg_connect( "$host $port $dbname $credentials"  );
      echo "Error : Unable to open database\n";
   } else {
      echo "Opened database successfully\n";

Then try to run it via command line with this command,

$ php db_connection.php

If it shows following output,

PHP Fatal error:  Call to undefined function pg_connect()

Need to install this package,

$ sudo apt-get install php5-pgsql

After that try again. If you received, Opened database successfully means you successfully connect and your database credential is correct. Otherwise, follow this steps to reset your db password for your own username.

$ sudo -u user_name psql db_name
$ alter user user_name with password 'new_password';

Now try again with changing credentials in a php file and it should work.