Handling and displaying large datasets is a common task in web development. To improve user experience and optimize system performance, it's often necessary to implement sorting and pagination in tables. This article explains how to achieve these features using PHP, with complete example code provided.
Sorting allows users to arrange data in ascending or descending order based on specific fields. Here's an example:
<?php // Get sorting field and order $sortField = isset($_GET['sort']) ? $_GET['sort'] : 'id'; $sortOrder = isset($_GET['order']) && $_GET['order'] == 'desc' ? 'desc' : 'asc'; // Sort the data based on field and order usort($data, function($a, $b) use ($sortField, $sortOrder) { if ($a[$sortField] == $b[$sortField]) { return 0; } if ($sortOrder == 'asc') { return ($a[$sortField] < $b[$sortField]) ? -1 : 1; } else { return ($a[$sortField] > $b[$sortField]) ? -1 : 1; } }); // Display table echo '<table>'; foreach ($data as $row) { echo '<tr>'; echo '<td>' . $row['id'] . '</td>'; echo '<td>' . $row['name'] . '</td>'; echo '<td>' . $row['age'] . '</td>'; echo '</tr>'; } echo '</table>'; ?>
In this example, the usort() function is used to sort the data. The callback function compares array elements based on the selected field and sorting order. The sorted data is then rendered into the table using a loop.
For large datasets, pagination is necessary to load data on demand and improve page performance. Here’s an example:
<?php // Get current page and items per page $page = isset($_GET['page']) ? $_GET['page'] : 1; $perPage = 10; // Calculate the data range for the current page $start = ($page - 1) * $perPage; $end = $start + $perPage; $dataToShow = array_slice($data, $start, $perPage); // Display table echo '<table>'; foreach ($dataToShow as $row) { echo '<tr>'; echo '<td>' . $row['id'] . '</td>'; echo '<td>' . $row['name'] . '</td>'; echo '<td>' . $row['age'] . '</td>'; echo '</tr>'; } echo '</table>'; // Display pagination links $totalPages = ceil(count($data) / $perPage); for ($i = 1; $i <= $totalPages; $i++) { echo '<a href="?page=' . $i . '">' . $i . '</a>'; } ?>
Pagination is achieved by calculating the start and end range based on the current page and items per page, then using array_slice() to extract the required subset of data. Pagination links are generated in a loop so users can navigate between pages easily.
This article has demonstrated how to implement table data sorting and pagination using PHP. These features help developers efficiently manage and display large datasets while enhancing user experience. The example code can be adapted and optimized according to your specific project requirements.