How can a PHP script be executed during the first page load to ensure a dynamically generated table appears sorted?

To ensure a dynamically generated table appears sorted on the first page load, you can use PHP to sort the data before generating the table. This can be achieved by retrieving the data from the database, sorting it based on a specific column, and then displaying the sorted data in the table.

<?php

// Retrieve data from the database
$data = fetchDataFromDatabase();

// Sort the data based on a specific column
usort($data, function($a, $b) {
    return $a['column_name'] - $b['column_name'];
});

// Generate the table with the sorted data
echo '<table>';
foreach ($data as $row) {
    echo '<tr>';
    echo '<td>' . $row['column_name'] . '</td>';
    // Add more columns as needed
    echo '</tr>';
}
echo '</table>';

function fetchDataFromDatabase() {
    // Code to fetch data from the database
    // Return the data as an array
}

?>