How can you effectively paginate a long table in PHP to display a limited number of rows per page?
When dealing with a long table in PHP, you can effectively paginate the data to display a limited number of rows per page by using a combination of SQL queries and PHP logic. You can use the LIMIT clause in your SQL query to fetch a specific subset of rows for each page, and then use PHP to handle the pagination links and display the data accordingly.
<?php
// Establish a database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Define the number of rows to display per page
$rows_per_page = 10;
// Get the current page number
if (isset($_GET['page']) && is_numeric($_GET['page'])) {
$page = $_GET['page'];
} else {
$page = 1;
}
// Calculate the starting row for the query
$start = ($page - 1) * $rows_per_page;
// Fetch data from the database with pagination
$sql = "SELECT * FROM your_table LIMIT $start, $rows_per_page";
$result = $conn->query($sql);
// Display the data in a table
echo "<table>";
while ($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row['column1'] . "</td><td>" . $row['column2'] . "</td></tr>";
}
echo "</table>";
// Pagination links
$total_pages = ceil($total_rows / $rows_per_page);
for ($i = 1; $i <= $total_pages; $i++) {
echo "<a href='your_page.php?page=$i'>$i</a> ";
}
$conn->close();
?>
Keywords
Related Questions
- What are the potential pitfalls of using reserved words in PHP class names, especially when working with namespaces?
- What potential issues can arise when using regular expressions with preg_match in PHP?
- How can global variables be effectively used in PHP functions to manage data across different parts of a script?