How can the code snippet provided be optimized for better performance and reliability in PHP?

The code snippet can be optimized for better performance and reliability by using prepared statements to prevent SQL injection attacks and improve query execution efficiency. Prepared statements also help in reusing query templates, reducing parsing time, and enhancing security by separating SQL logic from data.

// Optimized code snippet using prepared statements
$pdo = new PDO("mysql:host=localhost;dbname=myDB", "username", "password");

$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
$stmt->bindParam(':username', $username);
$stmt->execute();

$result = $stmt->fetchAll(PDO::FETCH_ASSOC);

foreach($result as $row) {
    echo $row['username'] . "<br>";
}