"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Limit Pagination Links in PHP with a Smart Pagination Algorithm?

How to Limit Pagination Links in PHP with a Smart Pagination Algorithm?

Published on 2024-11-08
Browse:711

How to Limit Pagination Links in PHP with a Smart Pagination Algorithm?

Smart Pagination Algorithm

When implementing pagination, it's often desirable to limit the number of page links displayed to avoid overwhelming the user. This can be achieved by using a "smart" pagination algorithm that only shows a few adjacent pages to the current page.

Example Algorithm

The following PHP code demonstrates a smart pagination algorithm that truncates the page list to show only two adjacent pages to the current page:

query("SELECT * FROM mytable LIMIT $start, $limit")
    ->fetchAll();

// Calculate total number of pages
$total_pages = count($data);

// Setup page variables
$prev = $page - 1;
$next = $page   1;
$lastpage = ceil($total_pages / $limit);
$lpm1 = $lastpage - 1;

// Generate pagination markup
$pagination = "";

if ($lastpage 

This algorithm uses the adjacents variable to control the number of adjacent pages shown on each side of the current page. It also includes the following features:

  • Ellipsis: If there are more pages than can be displayed, it uses an ellipsis to truncate the page list.
  • First and last pages: It always shows the first and last pages, regardless of the current page.
  • Disabled buttons: It disables the previous and next buttons when the current page is the first or last page, respectively.
  • Active class: It adds the "active" class to the current page's link.
Release Statement This article is reprinted at: 1729152507 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3