[英]Pagination display issue with number pages
hey guys my English is not very good 'but i try to explain my self clear. 嘿,我的英语不是很好'但是我尝试解释清楚自己的意思。 i'm creating pagination and all of my code is working perfect.
我正在创建分页,并且我所有的代码都运行良好。
The problem is, that i want to display only five numbers of pages and on click on next button i hide one and showing new one. 问题是,我只想显示五个页面,然后单击下一步按钮就隐藏了一个页面并显示了新页面。 it's looks like that.
看起来像那样。
next 12345 prev
next 23456 prev
Thank's for advice guys. 谢谢大家的建议。
Here is my code : 这是我的代码:
<?php
$dbh = new PDO("mysql:host=localhost;dbname=northwind", "root", "123");
$query = $dbh->prepare("SELECT ContactName FROM Customers");
$query->execute();
$numRows = $query->rowCount();
if (isset($_GET['pn'])) {
$pn = $_GET['pn'];
} else {
$pn = 1;
}
$startPage = 1;
$perPage = 9;
$lastPage = ceil($numRows / $perPage);
if ($pn < 1) {
$pn = 1;
} else if ($pn > $lastPage) {
$pn = $lastPage;
}
$controls = '';
if ($pn != $lastPage) {
$controls .= '<a id="next" href="' . $_SERVER['PHP_SELF'] . '?pn=' . ($pn + 1) . '"> next </a>';
}
for ($i=1; $i <= $lastPage; $i++) {
if ($i == $pn) {
$background = ' red;';
} else {
$background = ' green;';
}
$controls .= '<a id="page_' . $i . '" data-page="' . $i . '" class="num" style="background:' . $background . ' " href="' . $_SERVER['PHP_SELF'] . '?pn=' . $i . '"> ' . $i . '</a>';
}
if ($pn != $startPage) {
$controls .= '<a href="' . $_SERVER['PHP_SELF'] . '?pn=' . ($pn - 1) . '"> prev </a>';
}
$controls .= "PAGE " . $pn . " of " . $lastPage ;
$limit = "LIMIT " . ($pn-1) * $perPage . ', ' . $perPage;
$query2 = $dbh->prepare("SELECT ContactName FROM Customers " . $limit . "");
$query2->execute();
$outputList = '';
while($row = $query2->fetch(PDO::FETCH_OBJ)){
$outputList .= '<h1>' . $row->ContactName . '</h1><hr />';
}
I would suggest you to use more easy approach. 我建议您使用更简单的方法。
Lets consider a page contains 25 results. 让我们考虑一个包含25个结果的页面。 That means: 1st Page range is: 1-25 2nd Page range is: 26-50 and so on..
这意味着:第一页范围是:1-25第二页范围是:26-50,依此类推。
Now when a user request page 2, we should display him the results of 25-49. 现在,当用户请求第2页时,我们应该向他显示25-49的结果。 this means the results of (page-1)*25 till page*25-1 = results in 25-49.
这意味着(第1页)* 25的结果直到第* 25-1页的结果= 25-49。
Now all we need is how to tell the SQL to take those into consideration. 现在我们所需要的就是如何告诉SQL将这些考虑在内。
SELECT ContactName FROM Customers LIMIT 25 OFFSET 25;
Will produce use the desired result. 将产生使用所需的结果。
Now all you need is just pass the requested page with pn
as you already did. 现在,您只需要像以前一样通过
pn
传递请求的页面即可。 And print the next 1-3(whatever) next\\prev pages. 并打印接下来的1-3(无论如何)下一页\\上一页。
To know how many pages there are, just do another count
sql query that will give you the result and divide it by 25. 要知道有多少页,只需执行另一个
count
sql查询,它将为您提供结果并将其除以25。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.