<code
class
=
"php"
><?php
$adjacents
= 2;
$limit
= 5;
$page
= (int)
$_GET
[
"page"
] ?? 1;
$start
= (
$page
- 1) *
$limit
;
$data
=
$db
->query(
"SELECT * FROM mytable LIMIT $start, $limit"
)
->fetchAll();
$total_pages
=
count
(
$data
);
$prev
=
$page
- 1;
$next
=
$page
+ 1;
$lastpage
=
ceil
(
$total_pages
/
$limit
);
$lpm1
=
$lastpage
- 1;
$pagination
=
"<nav aria-label='page navigation'><ul class='pagination'>"
;
$pagination
.=
"<li class='page-item"
. (
$page
=== 1 ?
" disabled"
:
""
) .
"'><a class='page-link' href='?page=$prev'>« previous</a></li>"
;
$pagination
.=
"<li class='page-item"
. (
$page
<= 2 ?
" active"
:
""
) .
"'><a class='page-link' href='?page=1'>1</a></li>"
;
$pagination
.=
"<li class='page-item"
. (
$page
<= 3 ?
" active"
:
""
) .
"'><a class='page-link' href='?page=2'>2</a></li>"
;
$pagination
.=
"<li class='page-item disabled'><span class='page-link'>...</span></li>"
;
if
(
$lastpage
> 5 + (
$adjacents
* 2)) {
if
(
$page
< 1 + (
$adjacents
* 2)) {
for
(
$i
= 3;
$i
<= 4 + (
$adjacents
* 2);
$i
++) {
$pagination
.=
"<li class='page-item"
. (
$i
===
$page
?
" active"
:
""
) .
"'><a class='page-link' href='?page=$i'>$i</a></li>"
;
}
}
elseif
(
$lastpage
- (
$adjacents
* 2) >
$page
&&
$page
> (
$adjacents
* 2)) {
for
(
$i
=
$page
-
$adjacents
;
$i
<=
$page
+
$adjacents
;
$i
++) {
$pagination
.=
"<li class='page-item"
. (
$i
===
$page
?
" active"
:
""
) .
"'><a class='page-link' href='?page=$i'>$i</a></li>"
;
}
}
else
{
$pagination
.=
"<li class='page-item"
. (
$lpm1
===
$page
?
" active"
:
""
) .
"'><a class='page-link' href='?page=$lpm1'>$lpm1</a></li>"
;
$pagination
.=
"<li class='page-item"
. (
$lastpage
===
$page
?
" active"
:
""
) .
"'><a class='page-link' href='?page=$lastpage'>$lastpage</a></li>"
;
}
}
else
{
for
(
$i
= 3;
$i
<=
$lastpage
;
$i
++) {
$pagination
.=
"<li class='page-item"
. (
$i
===
$page
?
" active"
:
""
) .
"'><a class='page-link' href='?page=$i'>$i</a></li>"
;
}
}
$pagination
.=
"<li class='page-item disabled'><span class='page-link'>...</span></li>"
;
$pagination
.=
"<li class='page-item"
. (
$page
>=
$lastpage
- 2 ?
" active"
:
""
) .
"'><a class='page-link' href='?page=$lpm1'>$lpm1</a></li>"
;
$pagination
.=
"<li class='page-item"
. (
$page
>=
$lastpage
- 1 ?
" active"
:
""
) .
"'><a class='page-link' href='?page=$lastpage'>$lastpage</a></li>"
;
$pagination
.=
"<li class='page-item"
. (
$page
>=
$lastpage
?
" disabled"
:
""
) .
"'><a class='page-link' href='?page=$next'>next »</a></li>"
;
$pagination
.=
"</ul></nav>"
;
if
(
$lastpage
<= 1) {
$pagination
=
""
;
}
echo
$pagination
;
foreach
(
$data
as
$row
) {
}
echo
$pagination
;</code>