How can PHP handle errors when querying a database and displaying results in an HTML form?

When querying a database and displaying results in an HTML form using PHP, it is important to handle errors that may occur during the query execution. One way to do this is by using try-catch blocks to catch any exceptions thrown by the database query. Within the catch block, you can display an error message to the user or log the error for further investigation.

<?php
try {
    // Connect to the database
    $conn = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
    
    // Execute the query
    $stmt = $conn->query("SELECT * FROM mytable");
    
    // Display results in an HTML form
    // ...
    
} catch (PDOException $e) {
    echo "Error: " . $e->getMessage();
}
?>