php分页封装和调用的有哪些方法
在PHP中,可使用以下方法来封装和调用分页功能:
Pagination
的类,该类将包括分页所需的各种属性和方法。下面是一个简单的PHP分页封装和调用的示例代码:
// Pagination.php
class Pagination {
private $currentPage;
private $perPage;
private $totalRecords;
public function init($currentPage, $perPage, $totalRecords) {
$this->currentPage = $currentPage;
$this->perPage = $perPage;
$this->totalRecords = $totalRecords;
}
public function getTotalPages() {
return ceil($this->totalRecords / $this->perPage);
}
public function generateLinks($linkFormat) {
$totalPages = $this->getTotalPages();
$links = '';
for ($i = 1; $i <= $totalPages; $i++) {
$links .= sprintf($linkFormat, $i);
}
return $links;
}
}
// index.php
include 'Pagination.php';
// Create pagination object
$pagination = new Pagination();
// Initialize pagination
$pagination->init(1, 10, 100); // Assuming 10 records per page and 100 total records
// Generate pagination links
$linkFormat = '%d ';
$links = $pagination->generateLinks($linkFormat);
// Query database and display current page's data
$currentPage = $pagination->getCurrentPage();
$perPage = $pagination->getPerPage();
$offset = ($currentPage - 1) * $perPage;
$query = "SELECT * FROM table LIMIT $offset, $perPage";
// Execute the query and display the data
// ...
在上述示例中,Pagination
类封装了分页的相关属性和方法。在index.php
文件中,首先导入Pagination.php
文件,然后创建一个Pagination
对象,并使用init
方法初始化分页的初始值。接下来,可以调用generateLinks
方法生成份页链接,并通过$linkFormat
参数指定链接的格式。最后,根据当前页码和每页显示数量,履行相应的查询语句获得当前页的数据。
TOP