composer require yidas/pagination
index.php
,先 use
該物件,use
的目的只是可以用比較簡短的方式來呼叫物件。
<?php
use yidas\data\Pagination;
$totalCount
:資料總筆數,需要自己寫程式去計算(此物件需要 totalCount
參數,名稱不能改)$perPage
:每頁要呈現幾筆,可直接在 config.php
加個設定(此物件需要 perPage
參數,名稱不能改)$page
:現在在那一頁?此值應該會從網址傳進來,預設應為 1(此物件會自己抓設定,無須我們自行處理)config.php
,多一個「每頁顯示文章數」的設定,方便日後調整,暫時預設為 3 筆
// 每頁顯示文章數
$perPage = 3;
index.php
,在讀出文章之前,先來處理分頁的部份。首先要抓出文章總數 $total
,分頁工具才能用它來計算出頁數
<?php
use yidas\data\Pagination;
require_once 'header.php';
// 計算總資料數
try {
$stmt = $pdo->prepare('SELECT count(*) FROM `news`');
$stmt->execute();
list($totalCount) = $stmt->fetch(PDO::FETCH_NUM);
} catch (PDOException $e) {
die("計算總資料數失敗:" . $e->getMessage());
}
// 產生分頁物件
$pagination = new Pagination(['totalCount' => $totalCount, 'perPage' => $perPage]);
$pagination->offset
及抓取筆數 $pagination->limit
,便可利用資料庫的 LIMIT
來取得此範圍內的所有文章
try {
// 準備SQL語句
$sql = "SELECT * FROM `news` ORDER BY `date` DESC LIMIT ?, ?";
// 預備語句
$stmt = $pdo->prepare($sql);
// 綁定參數並執行語句
$stmt->execute([$pagination->offset, $pagination->limit]);
$all_news = [];
$news = $stmt->fetchAll();
foreach ($news as $row) {
$media = $row['media'];
unset($row['media']);
$row = array_map('htmlspecialchars', $row);
$row['files'] = json_decode($media, true);
$all_news[] = $row;
}
$smarty->assign('all_news', $all_news);
} catch (PDOException $e) {
echo "資料庫連接錯誤:" . $e->getMessage();
}
yidas\widgets\Pagination
的物件來產生。::widget()
將分頁物件丟進去即可產生
// 計算總資料數
try {
$stmt = $pdo->prepare('SELECT count(*) FROM `news`');
$stmt->execute();
list($totalCount) = $stmt->fetch(PDO::FETCH_NUM);
// 產生分頁物件
$pagination = new Pagination(['totalCount' => $totalCount, 'perPage' => $perPage]);
// 產生分頁工具列
$paginator = yidas\widgets\Pagination::widget(['pagination' => $pagination]);
$smarty->assign('paginator', $paginator);
} catch (PDOException $e) {
die("計算總資料數失敗:" . $e->getMessage());
}
最後記得將之送至樣板
index_content.tpl
,在最下方加入分頁工具列:
{foreach $all_news as $news}
<div class="row">
<div class="col-md-9">
<h3><a href="index.php?op=show&id={$news.id}">{$news.title}</a></h3>
<p>{$news.author}</p>
<p>{$news.date} 點閱數:{$news.views}</p>
<p>{$news.content|truncate:180:"..."}</p>
</div>
<div class="col-md-3">
{if is_file(reset($news.files))}
<img src="{reset($news.files)}" alt="" class="img-thumbnail"
style="object-fit: cover; width: 100%; height: 200px;">
{else}
<img src="https://picsum.photos/seed/picsum/400/400" alt="" class="img-thumbnail"
style="object-fit: cover; width: 100%; height: 200px;">
{/if}
</div>
</div>
{/foreach}
{$paginator}