What are some best practices for separating database queries from HTML output in PHP scripts to ensure better maintainability and readability?

Separating database queries from HTML output in PHP scripts can improve maintainability and readability by adhering to the principle of separation of concerns. One common approach is to use a template engine like Twig to handle the HTML output while keeping the database queries in separate PHP files or classes. This helps to organize code more effectively and makes it easier to update or modify either the database queries or the HTML output without affecting the other.

// Separate file for database queries (db_queries.php)
<?php

function getProducts() {
    // Database query to fetch products
    $products = $pdo->query('SELECT * FROM products')->fetchAll();
    
    return $products;
}
```

```php
// Using Twig for HTML output (index.php)
<?php

require_once 'vendor/autoload.php';

$loader = new Twig_Loader_Filesystem('templates');
$twig = new Twig_Environment($loader);

$products = getProducts(); // Call the function from db_queries.php

echo $twig->render('index.html', ['products' => $products]);