How to connect Postgre SQL with PHP
Code for PostgreSQL connection with PHP
<?php
// Database configuration
$host = 'localhost';
$db = 'database_name';
$user = 'postgres'; // by default its postgres
$pass = 'database_user_password';
$port = '5432'; // Default port for PostgreSQL
// Create connection string
$conn_string = "host=$host port=$port dbname=$db user=$user password=$pass";
// Establish a connection to the PostgreSQL database
$conn = pg_connect($conn_string);
if (!$conn) {
echo "Error: Unable to open database\n";
exit;
}
1. In the below we can define our hostname. For local, you can use localhost. If you want to access the other host then put that hostname or Server IP here
$host = 'localhost';
2. Here we define our database name
$db = 'database_name';
3. This code for DB user name. For local we use postgre its default username. But you can create db user name whatever you want.
$user = 'postgres';
4. Here we can define db password.
$pass = 'database_user_password';
5. Here we can define the Postgre post number. By default port no is 5432
$port = '5432';
6. The pg_connect function opens a new connection to the MySQL server.
// Create connection string
$conn_string = "host=$host port=$port dbname=$db user=$user password=$pass";
// Establish a connection to the PostgreSQL database
$conn = pg_connect($conn_string);
NOTE: For using Postgre Database with PHP, you need to enable the pgsql extension in php.in.
