How can PHP code be optimized for security and efficiency when accessing data from a database?

To optimize PHP code for security and efficiency when accessing data from a database, it is important to use prepared statements to prevent SQL injection attacks and to minimize the amount of data retrieved from the database to improve performance.

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

// Minimizing data retrieval
$stmt = $pdo->query("SELECT id, username FROM users");
while ($row = $stmt->fetch()) {
    echo "User ID: " . $row['id'] . ", Username: " . $row['username'] . "<br>";
}