John Davidson

How to show first 3 and last 3 pages in php pagination

0 comments
Message:


I create php pagination for articles it shows all pages over 1k and getting longers.


I want to do something like this prev 1234 ... 9999 next.


I tried this answer Limit pagination page number but could not make it work.


codes :


  if(isset($_POST['records-limit'])){
$CurrentPage['records-limit'] = $_POST['records-limit'];
}

$limit = isset($CurrentPage['records-limit']) ? $CurrentPage['records-limit'] : 10;
$page = (isset($_GET['page']) && is_numeric($_GET['page']) ) ? $_GET['page'] : 1;
$paginationStart = ($page - 1) * $limit;
$authors = $db->getPosts("SELECT * FROM posts LEFT JOIN users ON posts.post_userId = users.user_id LIMIT $paginationStart, $limit")->fetchAll();

// Get total records
$sql = $db->getPosts("SELECT count(post_id) AS post_id FROM posts")->fetchAll();
$allRecrods = $sql[0]['post_id'];

// Calculate total pages
$totoalPages = ceil($allRecrods / $limit);

// Prev + Next
$prev = $page - 1;
$next = $page + 1;

Pagination


<ul class="pagination justify-content-end">
<li class="page-item <?php if($page <= 1){ echo 'disabled'; } ?>">
<a class="page-link" href="<?php if($page <= 1){ echo '#'; } else { echo "?page=" . $prev; } ?>">Geri</a>
</li>
<?php for($i = 1; $i <=$totoalPages; $i++ ): ?>

<li class="page-item <?php if($page == $i) {echo 'active'; } ?>">
<a class="page-link" href="posts.php?page=<?php echo $i; ?>"> <?php echo $i; ?> </a>
</li>
<?php endfor; ?>

<li class="page-item <?php if($page >= $totoalPages) { echo 'disabled'; } ?>">
<a class="page-link" href="<?php if($page >= $totoalPages){ echo '#'; } else {echo "?page=". $next; } ?>">İleri</a>
</li>
</ul>


My Answer:
Here is a way to show the first 3 and last 3 pages in PHP pagination:

php
$totalPages = 100; // Total number of pages
$currentPage = isset($_GET['page']) ? $_GET['page'] : 1; // Current page number

$firstPage = max(1, $currentPage - 2);
$lastPage = min($totalPages, $currentPage + 2);

echo 'First';

for ($i = $firstPage; $i <= $lastPage; $i++) {
echo '' . $i . '';
}

echo 'Last';


This code will display links to the first 3 and last 3 pages, with the current page in the middle. You can adjust the number of pages shown by changing the values in the `max()` and `min()` functions.

Rate this post

3 of 5 based on 9858 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us