2010年10月9日 星期六

[PHP]-自製換頁

要做換頁功能時,要先準備好一些變數,
才能正確的擷取目前的資料範圍。
假設使用sqlite資料庫,程式碼如下:
    $dbh = new PDO('sqlite:question.db');
    // 取得資料總筆數
    $rs = null;
    $num = null;
    $sth0 = $dbh->query("SELECT count(*) FROM questions");
    $rs = $sth0->fetch();
    $num = $rs[0];
    //echo $num;

    // 一頁顯示20筆資料
    $page_size = 20;
    // 總頁數(無條件進位)
    $page_count = ceil($num/$page_size);

    // 目前所在頁數($_GET['anchor']為使用者點擊所要前往的頁數)
    $page_index = 0;
    if ($_GET['anchor']) {
        $page_index = $_GET['anchor'];
    } else {
        $page_index = 1;
    }

    // 目前頁面起始資料編號
    $item_start = 0;
    if ($page_index == 1) {
        $item_start = 1;
    } else {
        $item_start = ($page_index-1)*$page_size+1;
    }

    // 目前頁面最後資料編號
    $item_end = $page_index*$page_size;
    if ($item_end > $num) {
        $item_end = $num;
    }

    // page bar 起始頁(根據page_index座落在那個區間來判斷)
    // 這裡設定page bar一次能顯示十個頁面的連結
    $page_start = 0;
    $start = 1;
    $end = 10;
    $count = 1;
    for ($count; $count<=ceil($page_count/10); $count++) {
        if ($page_index>=$start && $page_index<=$end) {
            $page_start = $start;
            break;
        } else {
            $start = $start + 10;
            $end = $end + 10;
        }
    }

    // page bar 最後頁
    $page_end = 0;
    if ($page_start+9 < $page_count) {
        $page_end = $page_start+9;
    } else {
        $page_end = $page_count;
    }

    // 根據目前頁面的資料範圍擷取範圍內資料
    $result = null;
    $sth1 = $dbh->prepare("SELECT * FROM questions 
                      WHERE id >= ".$item_start." AND id <= ".$item_end);
    $sth1->execute();
    $result = $sth1->fetchAll();
這裡是假設資料表的id欄位是從1開始的連續編號,如果不是的話,
上述根據頁面資料範圍擷取資料庫範圍內資料的方法則不適用。

再來概據選取頁面,在html中印出目前的page bar範圍:
<div>
  <?php
    if ($page_count > 0) {
      if ($page_start != 1) {
  ?>
  <a href="./list.php?anchor=>?php echo $page_start-1; ?>">上10頁</a>
  <?php
      }
      for ($page_start; $page_start<=$page_end; $page_start++) {
        if ($page_start == $page_index) {
          echo $page_start;
        } else {
  ?>
  <a href="./list.php?anchor=<?php echo $page_start; ?>"></a>
  <?php
        }
      }
      if ($page_end<$page_count) {
  ?>
  <a href="./list.php?anchor=<?php echo $page_end+1; ?>">下10頁</a>
  <?php
      }
    }
  ?>
</div>

下頁是實際頁面:

沒有留言:

張貼留言