How can PHP developers ensure proper error handling when connecting to MySQL databases?

When connecting to MySQL databases in PHP, developers can ensure proper error handling by using try-catch blocks to catch any exceptions that may occur during the connection process. This allows developers to handle errors gracefully and provide meaningful error messages to users. Additionally, developers can use the mysqli_connect_errno() and mysqli_connect_error() functions to retrieve specific error codes and messages from the MySQL server.

<?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();
}
?>