What are some common pitfalls when querying a database in PHP?

One common pitfall when querying a database in PHP is not properly sanitizing user input, which can lead to SQL injection attacks. To prevent this, always use prepared statements with parameterized queries to securely interact with the database.

// Using prepared statements to prevent SQL injection
$pdo = new PDO("mysql:host=localhost;dbname=myDB", $username, $password);

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

// Fetching results
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);