What potential pitfalls can arise when fetching and displaying data from a MySQL database in PHP?

One potential pitfall is SQL injection attacks, where malicious users can manipulate input to execute unauthorized SQL queries. To prevent this, always use parameterized queries or prepared statements to sanitize user input before executing SQL queries.

// Example of using parameterized queries to prevent SQL injection

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

// Prepare a statement with a placeholder for 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);

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