What are the potential pitfalls of including database queries in HTML output in PHP?

Including database queries in HTML output in PHP can lead to security vulnerabilities such as SQL injection attacks. To mitigate this risk, it is recommended to separate the database logic from the presentation layer by using a proper MVC (Model-View-Controller) architecture. This involves querying the database in the PHP code, processing the data, and then passing it to the HTML template for display.

// Example of separating database logic from presentation layer using MVC architecture

// Model - where the database queries are performed
class UserModel {
    public function getUsers() {
        // Perform database query to retrieve users
        $users = // result of database query
        
        return $users;
    }
}

// Controller - where the data processing happens
class UserController {
    public function getUsers() {
        $userModel = new UserModel();
        $users = $userModel->getUsers();
        
        // Pass data to the view for display
        $this->renderView('users.php', ['users' => $users]);
    }
    
    public function renderView($view, $data) {
        extract($data);
        include $view;
    }
}

// View - where the HTML output is generated
// users.php
foreach($users as $user) {
    echo '<div>' . $user['name'] . '</div>';
}