What are some best practices for handling errors in PHP code when querying a MySQL database?

When querying a MySQL database in PHP, it is important to handle errors properly to ensure that your code is robust and secure. One best practice is to use try-catch blocks to catch any exceptions that may occur during the database query process. Additionally, you can use the mysqli_error() function to retrieve detailed error messages from the database server, allowing you to troubleshoot and resolve issues more effectively.

try {
    $connection = new mysqli($host, $username, $password, $database);

    // Check for connection errors
    if ($connection->connect_error) {
        throw new Exception('Connection failed: ' . $connection->connect_error);
    }

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

    if ($result === false) {
        throw new Exception('Query failed: ' . $connection->error);
    }

    // Process query results

    $connection->close();
} catch (Exception $e) {
    echo 'Error: ' . $e->getMessage();
}