How can PHP scripts be structured to handle errors in database connection and query execution gracefully?

When handling errors in database connection and query execution in PHP, it is important to use try-catch blocks to gracefully catch and handle any exceptions that may occur. This allows for more controlled error handling and provides a way to display meaningful error messages to the user.

<?php

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

    $stmt = $pdo->prepare("SELECT * FROM mytable");
    $stmt->execute();

    while ($row = $stmt->fetch()) {
        // process the rows
    }

} catch (PDOException $e) {
    echo "Error: " . $e->getMessage();
}

?>