What are some common pitfalls of mixing database queries with HTML output in PHP code and how can this be improved for better code organization?

Mixing database queries with HTML output in PHP code can lead to messy and hard-to-maintain code. To improve code organization, it's recommended to separate concerns by using a proper MVC (Model-View-Controller) architecture. This involves moving database queries to the model layer, keeping HTML output in the view layer, and using controllers to handle the logic between the two.

// Example of separating concerns using MVC architecture

// Model (e.g., UserModel.php)
class UserModel {
    public function getUsers() {
        // Database query to get users
        return $users;
    }
}

// View (e.g., users_view.php)
foreach ($users as $user) {
    echo '<div>' . $user['name'] . '</div>';
}

// Controller (e.g., UserController.php)
$userModel = new UserModel();
$users = $userModel->getUsers();
include 'users_view.php';