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

When troubleshooting database connection issues in PHP, error reporting can be effectively used to identify the root cause of the problem. By enabling error reporting and displaying error messages, developers can pinpoint issues such as incorrect database credentials, server connectivity problems, or syntax errors in SQL queries. This information can then be used to make necessary adjustments and successfully establish a connection to the database.

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

// Database credentials
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

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

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