How can PHP beginners avoid common pitfalls when working with database queries and updates?

Beginners can avoid common pitfalls when working with database queries and updates by using prepared statements to prevent SQL injection attacks, properly sanitizing input data to prevent errors, and handling database connection errors gracefully. It is also important to validate user input before executing queries to ensure data integrity.

// Example code snippet using prepared statements to avoid SQL injection
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');

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

// Example code snippet sanitizing input data
$username = filter_var($_POST['username'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);

// Example code snippet handling database connection errors
try {
    $pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}