What are some common pitfalls to avoid when handling database queries in PHP scripts?

One common pitfall to avoid when handling database queries in PHP scripts is SQL injection. To prevent this, always use prepared statements with parameterized queries instead of directly inserting user input into SQL queries. Example PHP code snippet using prepared statements:

// Establish a database connection
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');

// Prepare a SQL statement with a placeholder for the user input
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");

// Bind the user input to the placeholder
$stmt->bindParam(':username', $_POST['username']);

// Execute the query
$stmt->execute();

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

// Loop through the results
foreach ($results as $row) {
    echo $row['username'] . '<br>';
}