Jump to content

Displaying only limited amount of pages in php pagination?


Go to solution Solved by kicken,

Recommended Posts

I am really sorry for the poorly asked question. I want the pagination display only 4 pages at the same time (2 previous and 2 next), like on this photo:

Example image of the paginary

This is how far I went with the coding:

?php
    //fetch all posts from posts table
    $query = "SELECT * FROM posts ORDER BY date_time DESC";
    $posts = mysqli_query($connection, $query);

    $posts_per_page = 1;

    $number_of_posts = mysqli_num_rows($posts);

    $number_of_pages = ceil($number_of_posts/$posts_per_page);

    if(!isset($_GET['page'])) {
        $page = 1;
    } else {
        $page = $_GET['page'];
    }

    $this_page_first_posts = ($page - 1) * $posts_per_page;

    $query = "SELECT * FROM posts LIMIT " . $this_page_first_posts . ', ' . $posts_per_page;
    $posts = mysqli_query($connection, $query);
    ?>

Displaying pagination:

    <div class="pagination">
        <?php
        if($page > 1) {
            echo '<a class="page__numbers" href="blog.php?page=' . ($page - 1) . '">Previous</a>';
        }
        for($p = 1; $p < $number_of_pages; $p++) {
            echo '<a class="page__numbers" href="blog.php?page=' . $p . '">' . $p . '</a> ';
        }
        if($p > $page) {
            echo '<a class="page__numbers" href="blog.php?page=' . ($page + 1) . '">Next</a>';
        }
        ?>
    </div>

It currently displays every single available pages, which is obviously unideal once the blog gets filled with content.

Every help is highly appreciated, have a nice day!  

Edited by imbruceter
Badly formatted
  • Solution

You are currently looping from 1 to $number_of_pages when displaying your page numbers.

12 minutes ago, imbruceter said:
for($p = 1; $p < $number_of_pages; $p++) {

What you want to do is loop from $page - 2 to $page + 2, taking care not to go below 0 or above $number_of_pages in the process.  Get your range of pages to loop over with some simple math and the help of the min/max functions then loop over that range. 

$start = max(1, $page - 2);
$end = min($number_of_pages, $page + 2);
for ($p=$start; $p<=$end; $p++){
  //...
}

 

  • Like 1
8 hours ago, kicken said:

You are currently looping from 1 to $number_of_pages when displaying your page numbers.

What you want to do is loop from $page - 2 to $page + 2, taking care not to go below 0 or above $number_of_pages in the process.  Get your range of pages to loop over with some simple math and the help of the min/max functions then loop over that range. 

$start = max(1, $page - 2);
$end = min($number_of_pages, $page + 2);
for ($p=$start; $p<=$end; $p++){
  //...
}

Wow, thank you a lot for helping me out! Exactly what I was looking for.

 

Here's another way of doing pagination :


/*
 * Pagination Format
 * Read all the data from the database table in an array format
 */
function readData($pdo, $table, $page, $perPage, $offset) {
    $sql = 'SELECT * FROM ' . $table . ' WHERE page=:page ORDER BY date_added DESC LIMIT :perPage OFFSET :blogOffset';
    $stmt = $pdo->prepare($sql); // Prepare the query:
    $stmt->execute(['perPage' => $perPage, 'blogOffset' => $offset, 'page' => $page]); // Execute the query with the supplied data:
    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
if (isset($_GET['page']) && !empty($_GET['page'])) {
    $current_page = urldecode($_GET['page']);
} else {
    $current_page = 1;
}

$per_page = 1; // Total number of records to be displayed:
/* Total number of records that NEEDS to be displayed */
$total_count = totalRecords($pdo, 'cms');


/* calculate the offset */
$offset = $per_page * ($current_page - 1);

/* calculate total pages to be displayed */
$total_pages = ceil($total_count / $per_page);

/* Figure out the Pagination Links */
$links = links_function('index.php', $current_page, $total_pages);

/* Finally, call for the data from the database table to display */
$cms = readData($pdo, 'cms', 'blog', $per_page, $offset);

The below code is just one of many ways in setting up on how to display the links :

There might be a few logic bugs in it as well as this is old code:

function previous_page ($current_page): bool|int
{
    $prev = $current_page - 1;
    return ($prev > 0) ? $prev : false;
}

#[Pure] function previous_link($url="index.php", $current_page)
{
    if(previous_page($current_page) !== false) {
        $links .= '<a href="' . $url . '?page=' . previous_page($current_page) . '">';
        $links .= "&laquo; Previous</a>";
    }
    return $links;
}

function next_page($current_page, $total_pages): bool|int
{
    $next = $current_page + 1;
    return ($next <= $total_pages) ? $next : false;
}

#[Pure] function next_link($url="index.php", $current_page, $total_pages)
{
    if(next_page($current_page, $total_pages) !== false) {
        $links .= '<a href="' . $url . '?page=' . next_page($current_page, $total_pages) . '">';
        $links .= "Next &raquo;</a>";
    }
    return $links;
}

#[Pure] function links_function($url="index.php", $current_page, $total_pages): string
{
    $links .= "<div class=\"pagination\">";
    $links .=previous_link($url, $current_page); // Display previous link if there are any
    if ($current_page <= $total_pages) {
        if ($current_page == 1) {
            $links .= "<a class='selected' href=\"$url?page=1\">1</a>";
        } else {
            $links .= "<a href=\"$url?page=1\">1</a>";
        }

        $i = max(2, $current_page - 5);
        if ($i > 2) {
            $links .= '<span class="three-dots">' . " ... " . '</span>';
        }
        for (; $i < min($current_page + 6, $total_pages); $i++) {
            if ($current_page == $i) {
                $links .= "<a class='selected' href=\"$url?page=$i\">$i</a>";
            } else {
                $links .= "<a href=\"$url?page=$i\">$i</a>";
            }

        }
        if ($i !== $total_pages) {
            $links .= '<span class="three-dots">' . " ... " . '</span>';
        }
        if ($i === $total_pages) {
            $links .= "<a href=\"$url?page=$total_pages\">$total_pages</a>";
        } elseif ($i == $current_page) {
            $links .= "<a class='selected' href=\"$url?page=$total_pages\">$total_pages</a>";
        } else {
            $links .= "<a href=\"$url?page=$total_pages\">$total_pages</a>";
        }

    }
    $links .= next_link('index.php', $current_page, $total_pages); // Display next link if there are any
    $links .= "</div>";
    return $links;
}

 

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.