How can error handling be improved in PHP when executing MySQL queries to provide more detailed error messages?

When executing MySQL queries in PHP, error handling can be improved by enabling error reporting, using try-catch blocks, and utilizing the mysqli_error() function to retrieve detailed error messages. By implementing these techniques, developers can easily identify and troubleshoot any issues that may arise during query execution.

// Enable error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Connect to MySQL database
$mysqli = new mysqli("localhost", "username", "password", "database");

// Execute query with error handling
try {
    $result = $mysqli->query("SELECT * FROM table");
    if (!$result) {
        throw new Exception($mysqli->error);
    }
    // Process query results
} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
}

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