PHP to display database query errors


try {
    // Execute the query
    $result = $mysqli->query($sql);

    // Check for errors
    if (!$result) {
        throw new Exception('Error executing the query: ' . $mysqli->error);
    }

    // Process the results
} catch (Exception $e) {
    // Handle the error gracefully
    echo 'An error occurred: ' . $e->getMessage();
}

This code demonstrates how to handle database query errors in PHP using try-catch blocks.

  1. Execute the query using the mysqli_query() function.

  2. Check for errors using the !$result condition. If the query fails, it will return FALSE, indicating an error.

  3. If an error occurs, throw an exception using the throw new Exception() statement. The exception message should include the error message retrieved from the mysqli_error() function.

  4. Catch the exception using a catch (Exception $e) block. Inside the catch block, handle the error by logging it, displaying it to the user, or taking other appropriate actions.

  5. To implement this effectively, ensure that you handle all potential errors that may occur during query execution. Customize the error handling based on your application’s requirements.