What best practices should be followed when structuring PHP code to ensure efficient data retrieval from a database?

When structuring PHP code to ensure efficient data retrieval from a database, it is important to use prepared statements to prevent SQL injection attacks, minimize the number of database queries by fetching only the necessary data, and utilize indexes on columns frequently used in queries for faster retrieval.

// Example of using prepared statements to retrieve data efficiently from a database
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");

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

$user = $stmt->fetch(PDO::FETCH_ASSOC);

// Use the fetched data
echo $user['username'];