What are the best practices for structuring PHP code to handle multiple database queries and display the results in a structured manner on a webpage?

When dealing with multiple database queries in PHP to display results on a webpage, it is best practice to use functions or classes to organize your code and make it more manageable. By structuring your code in a modular way, you can easily reuse and maintain it. Additionally, consider using prepared statements to prevent SQL injection attacks and improve performance.

<?php
// Function to establish database connection
function connectToDatabase() {
    $host = 'localhost';
    $username = 'username';
    $password = 'password';
    $dbname = 'database';

    $conn = new mysqli($host, $username, $password, $dbname);

    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }

    return $conn;
}

// Function to execute a SQL query
function executeQuery($conn, $sql) {
    $result = $conn->query($sql);

    if ($result === false) {
        die("Error executing query: " . $conn->error);
    }

    return $result;
}

// Example of using the functions above
$conn = connectToDatabase();

$sql = "SELECT * FROM users";
$result = executeQuery($conn, $sql);

// Display results on webpage
if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        echo "Name: " . $row['name'] . "<br>";
        echo "Email: " . $row['email'] . "<br>";
        echo "<br>";
    }
} else {
    echo "No results found";
}

$conn->close();
?>