How can the code be modified to display error messages in case of database connection or query failures?

To display error messages in case of database connection or query failures, you can use PHP's try-catch block to catch any exceptions thrown by the database connection or query execution. Within the catch block, you can then display the error message to the user.

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $stmt = $conn->prepare("SELECT * FROM table_name");
    $stmt->execute();

    while ($row = $stmt->fetch()) {
        // Process the fetched data
    }
} catch(PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}
?>