What are the best practices for connecting to a PostgreSQL database using PHP and ensuring successful connection?

When connecting to a PostgreSQL database using PHP, it is important to ensure that the connection is successful by following best practices. This includes properly configuring the connection parameters, handling errors effectively, and securely managing credentials.

<?php
$host = 'localhost';
$port = '5432';
$dbname = 'your_database_name';
$user = 'your_username';
$password = 'your_password';

try {
    $db = new PDO("pgsql:host=$host;port=$port;dbname=$dbname;user=$user;password=$password");
    echo "Connected to the database successfully";
} catch (PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}