What are some common pitfalls to avoid when retrieving and displaying data from a MySQL database in a PHP application?

One common pitfall to avoid when retrieving and displaying data from a MySQL database in a PHP application 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.

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

// Prepare a statement with a parameterized query
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');

// Bind the parameter and execute the query
$stmt->bindParam(':username', $_POST['username']);
$stmt->execute();

// Fetch and display the results
while ($row = $stmt->fetch()) {
    echo $row['username'] . '<br>';
}