How can a table generated within a while loop be output using a function in PHP?

To output a table generated within a while loop using a function in PHP, you can create a function that accepts the necessary data as parameters, generates the table within a while loop, and then returns the HTML content of the table. This way, you can call the function wherever you want to display the table.

<?php
// Function to generate and output the table
function generateTable($data) {
    $output = '<table>';
    while ($row = $data->fetch_assoc()) {
        $output .= '<tr>';
        foreach ($row as $value) {
            $output .= '<td>' . $value . '</td>';
        }
        $output .= '</tr>';
    }
    $output .= '</table>';
    
    return $output;
}

// Example usage
$data = $mysqli->query("SELECT * FROM table_name");
echo generateTable($data);
?>