假設文章表主鍵 id 為自增整數,且已發布文章的 ID 連續或不連續均可。當前文章 ID 為 $currentId。
WHERE id < $currentId ORDER BY id DESC LIMIT 1WHERE id > $currentId ORDER BY id ASC LIMIT 1<?php
// config.php 已建立 $pdo 實例
$currentId = (int)($_GET['id'] ?? 0);
if (!$currentId) die('無效文章 ID');
// 上一篇
$stmtPrev = $pdo->prepare("SELECT id, title FROM articles WHERE id < ? AND status = 1 ORDER BY id DESC LIMIT 1");
$stmtPrev->execute([$currentId]);
$prev = $stmtPrev->fetch(PDO::FETCH_ASSOC);
// 下一篇
$stmtNext = $pdo->prepare("SELECT id, title FROM articles WHERE id > ? AND status = 1 ORDER BY id ASC LIMIT 1");
$stmtNext->execute([$currentId]);
$next = $stmtNext->fetch(PDO::FETCH_ASSOC);
?>
<nav class="article-nav">
<?php if ($prev): ?>
<a href="article.php?id=<?php echo $prev['id']; ?>" class="prev">
← 上一篇:<?php echo htmlspecialchars($prev['title']); ?>
</a>
<?php else: ?>
<span class="disabled">← 已是第一篇</span>
<?php endif; ?>
<?php if ($next): ?>
<a href="article.php?id=<?php echo $next['id']; ?>" class="next">
下一篇:<?php echo htmlspecialchars($next['title']); ?> →
</a>
<?php else: ?>
<span class="disabled">已是最新篇 →</span>
<?php endif; ?>
</nav>
若需限制在同一分類(category_id)內翻頁:
$stmtPrev = $pdo->prepare("
SELECT id, title FROM articles
WHERE id < ? AND category_id = ? AND status = 1
ORDER BY id DESC LIMIT 1
");
$stmtPrev->execute([$currentId, $categoryId]);
id、status、category_id 建立複合索引:INDEX idx_nav (status, category_id, id)MAX(id) 子查詢,ORDER BY ... LIMIT 1 在有索引時極快。若業務要求按 published_at 排序而非 ID:
// 上一篇(發布時間更早)
WHERE published_at < ? AND status = 1 ORDER BY published_at DESC LIMIT 1
// 下一篇(發布時間更晚)
WHERE published_at > ? AND status = 1 ORDER BY published_at ASC LIMIT 1
需為 published_at 建立索引,並注意同一秒發布多篇文章的邊界處理(可輔助用 ID 斷 Tie)。