萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP 程式設計

ASP 計數器實作:Access 資料庫記錄總數/今日/本週訪客數

傳統 ASP 透過 Access 資料庫實作簡易計數器,支援總瀏覽數、當日瀏覽數、本週瀏覽數三層統計。以下提供完整程式碼與資料表結構。

資料庫結構 (count.mdb)

欄位名型別說明
id自動編號主鍵
hit數字 (長整數)總瀏覽數
dayhit數字今日瀏覽數
weekhit數字本週瀏覽數
lasthit日期/時間最後更新日期,用於判斷跨日/跨週

資料表名:site,預先插入一筆 id=1 的記錄。

count.asp 完整程式碼

<%@ Language=VBScript %><%
Option Explicit
Response.Buffer = True
Response.Expires = 0

Dim conn, rs, sql, id, tdate, lasthit, p_year, p_month, p_day, period_time

'--- 連線 ---
Set conn = Server.CreateObject("ADODB.Connection")
conn.Open "Driver={Microsoft Access Driver (*.mdb)};DBQ=" & Server.MapPath("count.mdb")

'--- 參數 ---
id = Request("id")
If id = "" Then id = 1

'--- 更新總計數 ---
conn.Execute "UPDATE site SET hit = hit + 1 WHERE id = " & id

'--- 讀取目前統計 ---
Set rs = conn.Execute("SELECT hit, dayhit, weekhit, lasthit FROM site WHERE id = " & id)
If rs.EOF Then Response.End

'--- 判斷是否跨日 ---
tdate = Year(Now) & "-" & Month(Now) & "-" & Day(Now)
lasthit = rs("lasthit")
If Trim(lasthit) = Trim(tdate) Then
    conn.Execute "UPDATE site SET dayhit = dayhit + 1 WHERE id = " & id
Else
    conn.Execute "UPDATE site SET dayhit = 1 WHERE id = " & id
End If
conn.Execute "UPDATE site SET lasthit = '" & tdate & "' WHERE id = " & id

'--- 判斷是否跨週 (簡易 7 天法) ---
p_year  = CInt(Year(Now)) - CInt(Year(lasthit))
p_month = CInt(Month(Now)) - CInt(Month(lasthit))
p_day   = CInt(Day(Now)) - CInt(Day(lasthit))
period_time = ((p_year * 12 + p_month) * 30 + p_day)
If period_time <= 7 Then
    conn.Execute "UPDATE site SET weekhit = weekhit + 1 WHERE id = " & id
Else
    conn.Execute "UPDATE site SET weekhit = 1 WHERE id = " & id
End If

'--- 輸出 JavaScript 供前端引用 ---
Response.ContentType = "text/javascript"
Response.Write "document.write('<tr><td width=""100%"">今日訪問 " & rs("dayhit") & " 次, 本週訪問 " & rs("weekhit") & " 次, 總訪問 " & rs("hit") & " 次</td></tr>');"

'--- 清理 ---
rs.Close : Set rs = Nothing
conn.Close : Set conn = Nothing
%>

前端引用方式

<script language="JavaScript" src="count.asp?id=1"></script>

放置於欲顯示統計的頁面任意位置,會以 `...` 形式輸出,請配合表格結構使用。

改良建議

  • 效能:Access 檔案鎖定嚴重,高流量請改用 SQL Server / Redis / 檔案鎖 (Application.Lock) 或直接寫入日誌再離線統計。
  • 準確度:週期判斷採簡易 30 天/月估算,建議改用 DateDiff("ww", lasthit, Now, vbMonday, vbFirstFourDays) 計算 ISO 週數。
  • 防刷:加入 Session/Cookie/IP+UserAgent 去重,避免同一使用者短時間重複請求疊加。
  • 編碼:頁面與資料庫皆建議使用 UTF-8,避免中文亂碼。
copyright © 萬盛學電腦網 all rights reserved