How can the code be modified to improve efficiency and security in PHP?

To improve efficiency and security in PHP, one can use prepared statements with parameterized queries to prevent SQL injection attacks. This approach also helps in optimizing database performance by reusing query execution plans. Additionally, using functions like password_hash() and password_verify() for password hashing enhances security by securely storing user passwords.

// Example of using prepared statements with parameterized queries to prevent SQL injection
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
$stmt->bindParam(':username', $username);
$stmt->execute();
$user = $stmt->fetch();

// Example of using password_hash() and password_verify() for password hashing
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
if (password_verify($password, $hashed_password)) {
    // Password is correct
} else {
    // Password is incorrect
}