doudouwen2763
doudouwen2763
2015-10-11 09:10

如何在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>";
    }
?>
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • duanlie2709 duanlie2709 6年前

    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?

    点赞 评论 复制链接分享