What is the best way to optimize the display of a large table on a PHP page?
When displaying a large table on a PHP page, it is important to optimize the display to improve performance and user experience. One way to achieve this is by implementing pagination, which allows the table to display a limited number of rows per page, reducing the amount of data loaded at once. This can be done using PHP to retrieve a subset of data from the database based on the current page number and display it in the table.
<?php
// Set the number of rows to display per page
$rowsPerPage = 10;
// Get the current page number from the URL query parameter
$page = isset($_GET['page']) ? $_GET['page'] : 1;
// Calculate the offset for the SQL query
$offset = ($page - 1) * $rowsPerPage;
// Perform a query to retrieve data from the database with pagination
$query = "SELECT * FROM table_name LIMIT $offset, $rowsPerPage";
$result = mysqli_query($connection, $query);
// Display the table with the retrieved data
echo "<table>";
while($row = mysqli_fetch_assoc($result)) {
echo "<tr>";
echo "<td>" . $row['column1'] . "</td>";
echo "<td>" . $row['column2'] . "</td>";
// Add more columns as needed
echo "</tr>";
}
echo "</table>";
// Display pagination links
$totalRows = mysqli_num_rows(mysqli_query($connection, "SELECT * FROM table_name"));
$totalPages = ceil($totalRows / $rowsPerPage);
for ($i = 1; $i <= $totalPages; $i++) {
echo "<a href='?page=$i'>$i</a> ";
}
?>