How to implement pagination in PHP

WBOY
Release: 2023-06-11 20:10:01
Original
3559 people have browsed it

In web applications, the paging function is very necessary when displaying large amounts of data. As a popular web development language, PHP naturally provides a paging implementation method. This article will introduce how to implement paging in PHP.

1. Obtain data

Before implementing paging, you need to obtain the data to be paging. Normally, we need to get data from the database. Here we assume that we use the MySQL database and encapsulate the database connection and query methods through PDO. The following is an example query method:

function query($sql, $params = []) { $dsn = "mysql:host=localhost;dbname=mydatabase;charset=utf8mb4"; $username = "myusername"; $password = "mypassword"; $options = [ PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION ]; try { $pdo = new PDO($dsn, $username, $password, $options); $stmt = $pdo->prepare($sql); $stmt->execute($params); return $stmt->fetchAll(PDO::FETCH_ASSOC); } catch (PDOException $e) { die("Database error: " . $e->getMessage()); } }
Copy after login

We can query data by calling this method, for example:

$result = query("SELECT * FROM mytable");
Copy after login

2. Calculate the total number of pages

After obtaining the data, next One step is to figure out the total number of pages. We can calculate the total number of pages through the following formula:

totalPages = ceil(totalItems / pageSize)
Copy after login

Among them, totalItems represents the total number of items, and pageSize represents the number of items displayed on each page.

In PHP, you can use the built-in ceil() function to round up. The example is as follows:

$totalItems = count($result); $pageSize = 10; $totalPages = ceil($totalItems / $pageSize);
Copy after login

3. Get the current page data

Next, we need Get the data to be displayed on the current page. For convenience, we can define a getPageData() function to obtain the current page data. This function needs to pass in the current page number $page and the number of entries displayed on each page $pageSize. The example is as follows:

function getPageData($data, $page, $pageSize) { $start = ($page - 1) * $pageSize; $end = $start + $pageSize; return array_slice($data, $start, $pageSize); }
Copy after login

This function will Calculate the starting position and ending position based on the current page number, and obtain the corresponding entries from the $data array through the array_slice() function. The example is as follows:

$data = query("SELECT * FROM mytable"); $pageData = getPageData($data, 2, 10); // 获取第2页,每页显示10条数据
Copy after login

4. Generate paging links

Finally The first step is to generate pagination links so that users can easily turn pages. We can generate paging links through the following steps:

  1. Generate page number links based on the total number of pages;
  2. Highlight the corresponding link based on the current page number;
  3. In Add a "previous page" link in front and a "next page" link in the end.

The following is a sample code:

function getPageLinks($currentPage, $totalPages) { $links = []; for ($i = 1; $i <= $totalPages; $i++) { $isActive = $i == $currentPage; $links[] = [ "page" => $i, "isActive" => $isActive, "url" => "?page=$i", ]; } $prevPage = $currentPage - 1; $nextPage = $currentPage + 1; if ($prevPage >= 1) { array_unshift($links, [ "page" => $prevPage, "isActive" => false, "url" => "?page=$prevPage", ]); } if ($nextPage <= $totalPages) { array_push($links, [ "page" => $nextPage, "isActive" => false, "url" => "?page=$nextPage", ]); } return $links; }
Copy after login

This function will generate the corresponding link array based on the current page number and the total number of pages, including the page number of each link and whether it is the current page , and the URL of the link. Add the "previous page" link in front of the link array and the "next page" link after it to get a complete paging link array.

Usage examples are as follows:

$totalPages = ceil($totalItems / $pageSize); $pageLinks = getPageLinks($currentPage, $totalPages);
Copy after login

So far, we have introduced all the steps on how to implement paging in PHP. Through the above method, only some simple mathematical calculations and array operations are needed to easily implement the paging function.

The above is the detailed content of How to implement pagination in PHP. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!