How can PHP developers improve error handling and messaging in their code, especially when dealing with database queries?

When dealing with database queries in PHP, developers can improve error handling and messaging by implementing try-catch blocks around their query execution code. This allows them to catch any potential exceptions that may occur during the query execution and provide more informative error messages to the user. Additionally, developers can use the mysqli_error() function to retrieve detailed error messages from the MySQL server and display them to the user.

<?php

// Establish database connection
$connection = new mysqli("localhost", "username", "password", "database");

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

// Attempt to execute a query
try {
    $result = $connection->query("SELECT * FROM users");
    if ($result) {
        // Process query results
    } else {
        throw new Exception("Query failed: " . $connection->error);
    }
} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
}

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

?>