How can the readability and efficiency of PHP code be improved, especially when dealing with database queries?

When dealing with database queries in PHP, readability and efficiency can be improved by using prepared statements to prevent SQL injection attacks and by separating the database logic from the rest of the code for better organization. Additionally, using object-oriented programming principles can help make the code more modular and easier to maintain.

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

// Separating database logic into a separate class for better organization
class Database {
    private $pdo;

    public function __construct($pdo) {
        $this->pdo = $pdo;
    }

    public function getUserByUsername($username) {
        $stmt = $this->pdo->prepare("SELECT * FROM users WHERE username = :username");
        $stmt->execute(['username' => $username]);
        return $stmt->fetch();
    }
}

// Using object-oriented programming principles for modular and maintainable code
$database = new Database($pdo);
$user = $database->getUserByUsername($username);