php

Connect to a PostgreSQL database with PHP PDO

In this tutorial, we are going to see how to connect to a PostgreSQL database with PHP PDO.

Before creating a connection to a PostgreSQL database server, you must have:

  • PostgreSQL server installed on your local system or on a remote server.
  • Database on the PostgreSQL server.
  • PostgreSQL account with a username and password to access the database.
  • PDO-PostgreSQL driver enabled on your web server.

 

Enable the PDO_PGSQL driver

The majority of PHP distributions include the PDO_PGSQL extension by default, so you don’t need to do any further configuration in PHP. However, if this is not the situation, you can enable the extension by modifying the php.ini file to uncomment the following line:

	
;extension=php_pdo_pgsql.dll

Just delete the semicolon (;) at the beginning and restart the Web server.
 

 

Script to connect to a PostgreSQL database with PHP PDO
<?php

    $host = 'localhost';
    $dbname = 'test';
    $username = 'postgres';
    $password = 'postgres';
 
	$dsn = "pgsql:host=$host;port=5432;dbname=$dbname;user=$username;password=$password";
	 
	try{
		 $conn = new PDO($dsn);
		 
		 if($conn){
			echo "Successfully connected to $dbname!";
		 }
	}catch (PDOException $e){
		 echo $e->getMessage();
	}
?>
 

How does the script work
  • To connect to a PostgreSQL database, you simply create a new connection object, which is an instance of the PDO class. When you create a new connection object, you transmit the DSN as an argument to its parameter.
  • The try catch statement is used to catch any exceptions that may occur when connecting to the PostgreSQL database. In the catch block, we display the error message if there is a problem with the connection.
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

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