分页在php

时间:2017-12-26 09:16:14

标签: php pagination

我试图以我想要的方式进行分页。目前,它工作正常但所有数字都在显示。加上总数是固定的。 我想以适当的方式实现分页。 我想让它充满活力。意味着它应该计算数据库中可用的最后一个日期的总页数。 的代码

        $joursParPage = 3;
        $joursTotales = '45';
        $pagesTotales = ceil($joursTotales/$joursParPage);
        if(isset($_GET['page']) AND !empty($_GET['page']) AND $_GET['page'] > 0 AND $_GET['page'] <= $pagesTotales) {
           $_GET['page'] = intval($_GET['page']);
           $pageCourante = $_GET['page'];
        } else {
           $pageCourante = 1;
        }
        $depart = ($pageCourante-1)*$joursParPage;



        for($i=$depart;$i<=$pageCourante*3;$i++) {
    ?>

        <h4 class="block-title">
            <span style="margin-right: 0px;">Actualités du <?php echo utf8_encode(strftime('%A %d %B %Y', strtotime('-'.$i.' day'))); ?></span>
        </h4>
        <?php 
        $date = strftime('%Y-%m-%d', strtotime('-'.$i.' day'));
        $videoDer = $bdd->prepare('SELECT * FROM videos WHERE date_video = ? ORDER BY id DESC');
        $videoDer->execute(array($date));
        while($vD = $videoDer->fetch()) { ?>

    <?php }
        $articleDer = $bdd->prepare('SELECT * FROM articles WHERE date_article = ? ORDER BY id DESC');
        $articleDer->execute(array($date));
    while($aD = $articleDer->fetch()) { ?>

    <?php } ?>
    <?php } ?>
    <div class="lien_page">
    <span class="page_titre"> Pages  </span>
 <?php
  for($l=1;$l<=$pagesTotales;$l++) {
     if($l == $pageCourante) {
        echo '<span class="pageActuelle">'.$l.'</span>';
     } else {
        echo ' <a href="index.php?page='.$l.'" class="lien_page">'.$l.'</a> ';
     }
  }
  ?>

1 个答案:

答案 0 :(得分:1)

嗯,你做的很重要

最好的方法是使用limit子句而不是for循环来访问特定的no记录,就像你正在做的那样。

$recordsPerPage = 5;
$currentPage    = (isset($_GET['page]) && $_GET['page'] > 0)?$_GET['page]:1;
if($currentPage == 1){
    $startRecord = 1;
}else{
    $startRecords   = (($currentPage - 1) * $recordsPerPage) + 1 
    // it will be 6 in case of Page=2
    // it will be 11 in case of Page 3
}

$date           = strftime('%Y-%m-%d', strtotime('-'.$i.' day'));
$videoDer       = $bdd->prepare('SELECT * FROM videos WHERE date_video = ? ORDER BY id DESC limit '.$startRecords.', '.$recordsPerPage);
$videoDer->execute(array($date));


// your query looks like
select *
from videos
where date_video = ''
order by id desc
limit 6,5;