What are some common pitfalls when using PHP to query databases and display results in a loop?

One common pitfall is not properly escaping user input before using it in a database query, which can lead to SQL injection attacks. To prevent this, always use prepared statements or parameterized queries when interacting with the database.

// Connect to the database
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');

// Prepare a statement with placeholders
$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 in a loop
while ($row = $stmt->fetch()) {
    echo $row['username'] . '<br>';
}