user5407341
user5407341

Reputation:

How to do pagination in PHP?

I'm trying to do pagination in PHP, everything seems to be working, except that next and previous links don't work, it's only when I manually insert the page number in the URL that it displays data from the database on the next page.

Here is my code:

This is where I initialised the perpage and page. These are at the beginning of the page.

<?php                                
        $per_page=4;
        if (isset($_GET['page'])) {
                $page = $_GET['page'];
        }
        else {
                $page=1;

        } 
            $page;
            echo $start_from = ($page-1) * $per_page;
        //$search = $_POST['search'];

?>

And this is for the next and previous links, those ones that display the results depending on what the user wants to see.

<?php                                
    $query = "select * from services";
    $result = mysqli_query($link, $query);                                
    $total_records = mysqli_num_rows($result);
    //Using ceil function to divide the total records on per page
    $total_pages = ceil($total_records / $per_page);
    $prev = $page - 1;
    if($page == 1){
            echo "<span align='right' class='inactive'>&larr; Prev</span>";
    }else{
            echo "<a href='livebands.php?page=$prev'><span class='paging-prev'>".'&larr; Prev'."</span></a>";
    }
    for ($i=1; $i<=2; $i++) {
            for ($i=1; $i<=$page; $i++) {
                    echo "<a href='livebands.php?page=$i'><span class='paging'>" .$i. "</span></a>";
            }                                        
    }
    $page++;
    if ($page>$total_pages){
        echo "<span align='right' class='inactive'>&rarr; Next</span>";
    }else{                                        
        echo "<a href='livebands.php?page=$page&per_page=$per_page'><span align='right' class='paging-next'>".'Next &rarr;'."</span></a>";
    }
?>

Upvotes: 1

Views: 174

Answers (1)

The fourth bird
The fourth bird

Reputation: 163207

If I use you code and hardcode the $total_records variable to 5 for example, the links seem to work.

// $query = "select * from services";
// $result = mysqli_query($link, $query);                                
// $total_records = mysqli_num_rows($result);
$total_records = 5;

Are you sure that your $total_records is more than 4?

Upvotes: 1

Related Questions