How can the modulo operator be used in PHP to control the distribution of data from a MySQL table into columns in an HTML table?

To control the distribution of data from a MySQL table into columns in an HTML table, you can use the modulo operator (%) in PHP to determine which column each data entry should be placed in. By calculating the remainder of the row number divided by the number of columns, you can evenly distribute the data across the columns.

<?php
// Assuming $result contains the data fetched from MySQL table
$num_columns = 3; // Number of columns in the HTML table

echo '<table>';
$i = 0;
while ($row = $result->fetch_assoc()) {
    if ($i % $num_columns == 0) {
        echo '<tr>'; // Start a new row
    }
    
    echo '<td>' . $row['column_name'] . '</td>'; // Output data in a table cell
    
    if ($i % $num_columns == $num_columns - 1) {
        echo '</tr>'; // End the current row
    }
    
    $i++;
}

// Check if there are any remaining cells to close the row
if ($i % $num_columns != 0) {
    echo '</tr>';
}

echo '</table>';
?>