How can PHP developers effectively handle errors related to database connections in their projects?

When handling errors related to database connections in PHP projects, developers can use try-catch blocks to catch exceptions thrown during connection attempts. This allows for graceful error handling and the ability to provide meaningful error messages to users. Additionally, developers can use functions like mysqli_connect_errno() and mysqli_connect_error() to retrieve specific error codes and messages from the database connection.

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

try {
    $conn = new mysqli($servername, $username, $password, $dbname);
    if ($conn->connect_error) {
        throw new Exception("Connection failed: " . $conn->connect_error);
    }
    echo "Connected successfully";
} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
}
?>