PHP Pagination: A Simple Script
Introduction
Managing data efficiently for web applications often involves implementing pagination to divide extensive data into manageable pages. This article provides a rudimentary script that enables pagination in PHP.
PHP Pagination Script
To avoid repeating the same code for separate pages, we utilize a combination of HTML and PHP. Here's the script:
<?php try { // Count total database rows $total = $dbh->query('SELECT COUNT(*) FROM table')->fetchColumn(); // Set pagination parameters $limit = 20; $pages = ceil($total / $limit); // Get current page number $page = filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT, ['options' => ['default' => 1, 'min_range' => 1]]); // Calculate query offset $offset = ($page - 1) * $limit; // Display pagination information $start = $offset + 1; $end = min(($offset + $limit), $total); $prevlink = ($page > 1) ? '<a href="?page=1" title="First page">«</a> <a href="?page=' . ($page - 1) . '" title="Previous page">‹</a>' : '<span class="disabled">«</span> <span class="disabled">‹</span>'; $nextlink = ($page < $pages) ? '<a href="?page=' . ($page + 1) . '" title="Next page">›</a> <a href="?page=' . $pages . '" title="Last page">»</a>' : '<span class="disabled">›</span> <span class="disabled">»</span>'; // Prepare paged query $stmt = $dbh->prepare(' SELECT * FROM table ORDER BY name LIMIT :limit OFFSET :offset '); $stmt->bindParam(':limit', $limit, PDO::PARAM_INT); $stmt->bindParam(':offset', $offset, PDO::PARAM_INT); $stmt->execute(); // Display results if ($stmt->rowCount() > 0) { $stmt->setFetchMode(PDO::FETCH_ASSOC); $iterator = new IteratorIterator($stmt); foreach ($iterator as $row) { echo '<p>' . $row['name'] . '</p>'; } } else { echo '<p>No results could be displayed.</p>'; } } catch (Exception $e) { echo '<p>' . $e->getMessage() . '</p>'; } ?>
Conclusion
This script employs HTML and PHP to dynamically display data over multiple pages, offering users a seamless and intuitive browsing experience.
The above is the detailed content of How to Implement Simple PHP Pagination for Web Applications?. For more information, please follow other related articles on the PHP Chinese website!