How can a developer ensure that data retrieved from a MySQL query is properly displayed outside of a class method in PHP?

To ensure that data retrieved from a MySQL query is properly displayed outside of a class method in PHP, the developer can store the query results in a variable within the class method and return that variable. Then, outside of the class method, the developer can call the method to retrieve the data and display it as needed.

class Database {
    private $connection;

    public function __construct($host, $username, $password, $database) {
        $this->connection = new mysqli($host, $username, $password, $database);
    }

    public function getDataFromQuery($query) {
        $result = $this->connection->query($query);
        $data = $result->fetch_all(MYSQLI_ASSOC);
        return $data;
    }
}

// Usage outside of the class method
$database = new Database('localhost', 'username', 'password', 'database');
$query = "SELECT * FROM table";
$data = $database->getDataFromQuery($query);

foreach ($data as $row) {
    echo $row['column_name'] . "<br>";
}