How can proper error handling and debugging techniques be implemented in PHP to troubleshoot database connection issues?

When troubleshooting database connection issues in PHP, proper error handling and debugging techniques can be implemented by using try-catch blocks to catch exceptions and display meaningful error messages. Additionally, enabling error reporting and logging can help identify the root cause of the problem.

<?php

try {
    $pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "Connected to database successfully!";
} catch (PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}

?>