首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

Smarty 分頁功能完整實現教程(PHP + MySQL)

     編輯:PHP 綜合知識

項目結構

project/
├── index.php          # 入口控制器
├── include.php        # Smarty 配置
├── conn.php           # 數據庫連接
└── templates/
    └── index.htm      # 模板文件

1. Smarty 核心配置

// include.php
require 'libs/Smarty.class.php';
$smarty = new Smarty();
$smarty->template_dir = 'templates/';
$smarty->compile_dir  = 'templates_c/';
$smarty->config_dir   = 'configs/';
$smarty->cache_dir    = 'cache/';
$smarty->caching = false; // 開發階段關閉緩存
$smarty->left_delimiter  = '{';  // 自定義分隔符避免與 JS 衝突
$smarty->right_delimiter = '}';

2. 數據庫連接

// conn.php
$conn = mysql_connect('localhost', 'root', 'password');
mysql_select_db('test_db', $conn);
mysql_query("SET NAMES utf8");

3. 控制器邏輯

// index.php
require 'include.php';
require 'conn.php';

$pageSize = 10;
$currentPage = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$offset = ($currentPage - 1) * $pageSize;

// 總記錄數
$totalRows = mysql_result(mysql_query("SELECT COUNT(*) FROM wp_links"), 0);
$totalPages = ceil($totalRows / $pageSize);

// 分頁導航構建
$pageUp = $pageDown = '';
if ($totalPages > 1) {
    if ($currentPage == 1) {
        $pageUp = '首頁';
        $pageDown = '<a href="?page=' . ($currentPage + 1) . '">下一頁</a>';
    } elseif ($currentPage == $totalPages) {
        $pageUp = '<a href="?page=' . ($currentPage - 1) . '">上一頁</a>';
        $pageDown = '末頁';
    } else {
        $pageUp = '<a href="?page=' . ($currentPage - 1) . '">上一頁</a>';
        $pageDown = '<a href="?page=' . ($currentPage + 1) . '">下一頁</a>';
    }
}
$pageInfo = "當前第 {$currentPage} 頁,共 {$totalPages} 頁";

// 數據查詢
$sql = "SELECT link_id, link_url, link_name FROM wp_links LIMIT {$offset}, {$pageSize}";
$res = mysql_query($sql);
$data = [];
while ($row = mysql_fetch_assoc($res)) {
    $data[] = $row;
}

// 模板賦值
$smarty->assign('title', $data);
$smarty->assign('pageup', $pageUp);
$smarty->assign('pagedown', $pageDown);
$smarty->assign('pageconfig', $pageInfo);
$smarty->display('index.htm');

4. 模板文件

<!-- templates/index.htm -->
<table border="1" cellpadding="5" cellspacing="0">
    <tr><th>ID</th><th>URL</th><th>Name</th></tr>
    {section name=list loop=$title}
    <tr>
        <td>{$title[list].link_id}</td>
        <td>{$title[list].link_url}</td>
        <td>{$title[list].link_name}</td>
    </tr>
    {/section}
</table>
<div class="pagination">
    {$pageup} {$pagedown} {$pageconfig}
</div>

進階優化:數字分頁導航

將分頁邏輯封裝為函數,生成類似 1 2 3 ... 10 的導航:

function buildPager($current, $total, $urlPattern) {
    if ($total <= 1) return '';
    $html = '<nav><ul class="pagination">';
    $range = 2; // 當前頁前後顯示頁數
    $start = max(1, $current - $range);
    $end = min($total, $current + $range);
    
    if ($start > 1) $html .= '<li><a href="' . sprintf($urlPattern, 1) . '">首頁</a></li>';
    if ($current > 1) $html .= '<li><a href="' . sprintf($urlPattern, $current-1) . '">«</a></li>';
    
    for ($i = $start; $i <= $end; $i++) {
        $active = $i == $current ? ' class="active"' : '';
        $html .= '<li' . $active . '><a href="' . sprintf($urlPattern, $i) . '">' . $i . '</a></li>';
    }
    
    if ($current < $total) $html .= '<li><a href="' . sprintf($urlPattern, $current+1) . '">»</a></li>';
    if ($end < $total) $html .= '<li><a href="' . sprintf($urlPattern, $total) . '">末頁</a></li>';
    $html .= '</ul></nav>';
    return $html;
}

// 使用
$pagerHtml = buildPager($currentPage, $totalPages, '?page=%d');
$smarty->assign('pager', $pagerHtml);

模板中直接輸出 {$pager} 即可。

注意事項

  • 生產環境請使用 PDO/MySQLi 預處理語句防止 SQL 注入。
  • 大數據量時,COUNT(*) 可改用緩存或近似值。
  • 分頁 URL 建議使用路由重寫(如 /page/3)利於 SEO。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved