What are the best practices for handling errors and error messages in PHP scripts, especially in the context of database interactions?

When handling errors and error messages in PHP scripts, especially in the context of database interactions, it is important to use try-catch blocks to catch exceptions and handle errors gracefully. Additionally, using functions like mysqli_error() or PDOException->getMessage() can help provide more detailed error messages for debugging purposes.

try {
    // Database connection and query execution
    $conn = new mysqli($servername, $username, $password, $dbname);
    
    if ($conn->connect_error) {
        throw new Exception("Connection failed: " . $conn->connect_error);
    }
    
    $result = $conn->query("SELECT * FROM users");
    
    if (!$result) {
        throw new Exception("Error executing query: " . $conn->error);
    }
    
    // Process query results
    
    $conn->close();
} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
}