What are the potential pitfalls of not properly handling database queries in PHP, as seen in the provided code snippet?

The potential pitfalls of not properly handling database queries in PHP include vulnerability to SQL injection attacks, data corruption, and inefficient query execution. To solve this issue, it is crucial to use parameterized queries or prepared statements to sanitize user input and prevent malicious code execution.

// Fix: Using prepared statements to handle database queries safely

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

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

// Bind the parameter value to the placeholder
$stmt->bindParam(':username', $username);

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

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

// Loop through the results
foreach ($results as $row) {
    // Handle the retrieved data
}