核心邏輯流程
- 查詢總記錄數
SELECT COUNT(*) 計算總頁數。
- 解析請求參數
txtPage,驗證合法性(空值、非數字、超範圍修正)。
- 構建帶
LIMIT offset, pageSize 的 SQL 取得當頁資料。
- 迴圈輸出記錄,配合自訂
ShowPageNum 函數渲染分頁導航條。
關鍵代碼片段
<%
Dim strSql, Rs, intRecordNum, intCurrentPage, intRowcount
intRowcount = 0
intPageCount = 15 ' 每頁15筆
GetConn_Open
Set Rs = Conn.Execute("SELECT COUNT(*) As intcounts FROM datainfo WHERE sort=1 AND flag_lm=1")
intRecordNum = IIf(Rs.EOF And Rs.BOF, 0, CInt(Rs("intcounts")))
' 計算總頁數
If (intRecordNum Mod intPageCount) > 0 Then
intTotalPages = Int(intRecordNum / intPageCount) + 1
Else
intTotalPages = intRecordNum / intPageCount
End If
' 當前頁碼驗證
intCurrentPage = 1
If Not (IsEmpty(Request("txtPage")) Or IsNull(Request("txtPage")) Or Trim(Request("txtPage"))="" Or Not IsNumeric(Request("txtPage")) Or Len(Request("txtPage"))>8) Then
If CLng(Request("txtPage")) < 1 Then intCurrentPage = 1
ElseIf CLng(Request("txtPage")) > intTotalPages Then intCurrentPage = intTotalPages
Else intCurrentPage = CLng(Request("txtPage"))
End If
' 取得當頁資料
strSql = "SELECT id,name,recreation,characteristic,address FROM datainfo WHERE sort=1 AND flag_lm=1 ORDER BY id DESC LIMIT " & (intCurrentPage-1)*intPageCount & "," & intPageCount
Set Rs = Server.CreateObject("ADODB.RecordSet")
Rs.Open strSql, Conn, 1, 1 ' adOpenKeyset, adLockReadOnly
' 輸出迴圈
Do While Not Rs.EOF And intRowcount < intPageCount
' ... 輸出 Rs("name") 等欄位 ...
Rs.MoveNext
intRowcount = intRowcount + 1
Loop
ShowPageNum intRecordNum, intTotalPages, intCurrentPage, intPageCount, Request.ServerVariables("SCRIPT_NAME"), "?"
Rs.Close: Set Rs = Nothing
%>
優化建議
- 使用參數化查詢防止 SQL 注入。
- 大數據量改用
ID > last_id 游標分頁替代 LIMIT offset。
- 分頁導航邏輯封裝為可復用 Include 檔案。