doudouwen2763 2015-10-11 09:10
浏览 20
已采纳

如何在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 2015-10-12 10:06
    关注

    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?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测