傳統 ASP 透過 Access 資料庫實作簡易計數器,支援總瀏覽數、當日瀏覽數、本週瀏覽數三層統計。以下提供完整程式碼與資料表結構。
| 欄位名 | 型別 | 說明 |
|---|---|---|
| id | 自動編號 | 主鍵 |
| hit | 數字 (長整數) | 總瀏覽數 |
| dayhit | 數字 | 今日瀏覽數 |
| weekhit | 數字 | 本週瀏覽數 |
| lasthit | 日期/時間 | 最後更新日期,用於判斷跨日/跨週 |
資料表名:site,預先插入一筆 id=1 的記錄。
<%@ 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>
放置於欲顯示統計的頁面任意位置,會以 `
DateDiff("ww", lasthit, Now, vbMonday, vbFirstFourDays) 計算 ISO 週數。