What are some best practices for connecting a PHP script to a PostgreSQL database?

When connecting a PHP script to a PostgreSQL database, it is best practice to use the PDO (PHP Data Objects) extension for secure and efficient database access. This involves setting up a connection to the PostgreSQL database using the PDO object and handling any potential errors that may occur during the connection process.

<?php
// PostgreSQL database credentials
$host = 'localhost';
$dbname = 'mydatabase';
$user = 'myuser';
$password = 'mypassword';

try {
    // Create a new PDO instance
    $pdo = new PDO("pgsql:host=$host;dbname=$dbname", $user, $password);
    
    // Set PDO to throw exceptions on error
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    // Perform database operations here
    
} catch (PDOException $e) {
    // Handle any connection errors
    echo "Connection failed: " . $e->getMessage();
}
?>