Database Reference
In-Depth Information
Use the counter method as follows:
count
=
get_hit_count
(
dbh
,
ENV
[
"SCRIPT_NAME"
]
)
page
<<
cgi
.
p
{
"This page has been accessed
#{
count
}
times."
}
The
recipes
distribution includes demonstration hit counter scripts in the
apache/
hits
directory (
tomcat/mcb
for JSP). Install any of these in your web tree, invoke it from
your browser a few times, and watch the count increase. First, you must create the
hitcount
table. To do this, use the
hits.sql
script provided in the
tables
directory. (The
script also creates the
hitlog
table because the hit-counting scripts implement hit log‐
ging as well, as discussed in
Recipe 20.13
.)
20.13. Web Page Access Logging
Problem
You want to know things about a page other than the number of times it's been accessed,
such as when accesses occur and the hosts from which requests originate.
Solution
Maintain a hit log rather than a simple counter.
Discussion
The
hitcount
table used in
Recipe 20.12
records only the access count for each page
registered in it. Suppose that you want to track other information about page access,
such as the time of access and client host for each request. In this case, you must log a
row for each page access rather than maintain only a count:
CREATE
TABLE
hitlog
(
path
VARCHAR
(
255
)
CHARACTER
SET
latin1
COLLATE
latin1_general_cs
NOT
NULL
,
t
TIMESTAMP
DEFAULT
CURRENT_TIMESTAMP
,
host
VARCHAR
(
255
),
INDEX
(
path
)
);
The
hitlog
table has the useful property that access times are recorded automatically
in the
TIMESTAMP
column
t
when you insert new rows (see
Recipe 6.7
). For notes on
choosing the character set and collation for the
path
column, see
Recipe 20.12
.
To insert new rows into the
hitlog
table, use this statement:
INSERT
INTO
hitlog
(
path
,
host
)
VALUES
(
path_val
,
host_val
);
For example, in a JSP page, log hits like this: