Skip to content
PHP Logo

Are there specific configuration settings or dependencies required for PHP to connect to PostgreSQL successfully?

To successfully connect PHP to PostgreSQL, you need to ensure that the PostgreSQL extension is installed and enabled in your PHP configuration file (php.ini). Additionally, you need to specify the correct host, port, database name, username, and password in your PHP script when creating a connection to PostgreSQL.

php
<?php
$host = 'localhost';
$port = '5432';
$dbname = 'mydatabase';
$user = 'myuser';
$password = 'mypassword';

$conn = pg_connect("host=$host port=$port dbname=$dbname user=$user password=$password");

if (!$conn) {
    echo "Failed to connect to PostgreSQL: " . pg_last_error();
} else {
    echo "Connected to PostgreSQL successfully";
}
?>