How can error handling be improved in the provided PHP code snippet to identify connection issues more effectively?

The issue with the current code is that it only checks for errors in the query execution, but not for errors related to the database connection itself. To improve error handling and identify connection issues more effectively, we can use the mysqli_connect_errno() function to check if there was an error connecting to the database.

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

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

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

// Perform query
$sql = "SELECT * FROM table";
$result = $conn->query($sql);

if (!$result) {
    die("Error executing query: " . $conn->error);
}

// Output data
while ($row = $result->fetch_assoc()) {
    echo "Name: " . $row["name"] . "<br>";
}

// Close connection
$conn->close();
?>