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);
?>
Keywords
Related Questions
- What are some common mistakes to avoid when working with dynamic form inputs in PHP, and how can they be rectified?
- What are the advantages of using stream_socket_* functions over cURL for network communication in PHP?
- What best practices should be followed when filtering out certain files in a PHP script?