How can error reporting be effectively utilized to troubleshoot PHP database connection issues?

To troubleshoot PHP database connection issues, error reporting can be effectively utilized by enabling error reporting in PHP to display any errors or warnings related to the database connection. This can help identify the specific issue causing the connection problem, such as incorrect credentials or server configuration.

// Enable error reporting for database connection debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Attempt to establish a database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

$conn = new mysqli($servername, $username, $password, $dbname);

// Check for connection errors
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} else {
    echo "Connected successfully";
}