Is there a guideline for determining whether PHP code should be placed in the head or body section of an HTML document?

It is generally recommended to place PHP code that generates dynamic content, such as database queries or session handling, before any HTML content in the body section. This ensures that the PHP code is executed before any HTML elements are rendered. However, PHP code that is purely for logic or processing can be placed in the head section. It is important to maintain a separation of concerns and keep presentation and logic separate.

<?php
// PHP code for database query
$db_connection = mysqli_connect("localhost", "username", "password", "database");
$query = "SELECT * FROM users";
$result = mysqli_query($db_connection, $query);

// HTML content to display user data
echo "<table>";
while ($row = mysqli_fetch_assoc($result)) {
    echo "<tr><td>" . $row['username'] . "</td></tr>";
}
echo "</table>";
?>