How can the code structure be improved to simplify the process of displaying data from MySQL in PHP?

The code structure can be improved by separating the database connection logic from the data retrieval and display logic. This can be achieved by creating a separate function to handle the database connection and query execution, and another function to handle the display of the retrieved data. By doing this, the code becomes more modular, easier to read, and maintain.

<?php

// Function to establish database connection and execute query
function getDataFromDatabase($query) {
    $conn = new mysqli("localhost", "username", "password", "database");

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

    $result = $conn->query($query);

    $conn->close();

    return $result;
}

// Function to display data retrieved from the database
function displayData($result) {
    if ($result->num_rows > 0) {
        while($row = $result->fetch_assoc()) {
            echo "Name: " . $row["name"] . "<br>";
            echo "Email: " . $row["email"] . "<br>";
            // Add more fields as needed
        }
    } else {
        echo "No results found";
    }
}

// Query to retrieve data from MySQL
$query = "SELECT * FROM users";
$data = getDataFromDatabase($query);

displayData($data);

?>