How can PHP beginners ensure that their database queries in PHP scripts are properly executed and error-handled?

PHP beginners can ensure that their database queries are properly executed and error-handled by using try-catch blocks to catch any exceptions that may occur during the query execution. Within the catch block, they can use the PDOException class to retrieve detailed error information and handle the error accordingly. Additionally, beginners should always sanitize user input to prevent SQL injection attacks.

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

    $stmt = $pdo->prepare("SELECT * FROM users WHERE id = :id");
    $stmt->bindParam(':id', $id);
    $stmt->execute();

    $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    echo "Error: " . $e->getMessage();
}