Coutning Hits With In Scoop
|
|
By bbatchel , Section Code [] Posted on Sun Feb 18, 2001 at 12:00:00 PM PST
|
|
One of the latest things I have implemented in
my scoop site is a hit counter.
I figured what better place to do it than in the same mysql database that scoop runs in. Below I will run through how to set one of these up in your own site.
|
The first thing we need to do is create the table in mysql. So log into the mysql client and issue the following create table statement:
create table hits(
hid char(20),
hits int(11));
Next we create a box which will do the following:
- If an entry for today's date exists in the table, increment it by one.
- If an entry for today's date does not exist, create an entry.
- Sum all of the previous hits for the total hit count.
The code for this:
my $content;
my ($rv, $sth) = $S->db_select({
WHAT => 'hits',
FROM => 'hits',
WHERE => 'hid = curdate()+0'});
if ($rv == 0)
{
$S->db_insert({
INTO => 'hits',
COLS => 'hid, hits',
VALUES => 'curdate()+0, 0'});
}
$S->db_update({
WHAT => 'hits',
SET => 'hits = hits + 1',
WHERE => 'hid = curdate()+0'});
my ($rv, $sth) = $S->db_select({
WHAT => 'hits',
FROM => 'hits',
WHERE => 'hid = curdate()+0'});
my $hitstoday = $sth->fetchrow_hashref();
$content = qq{$hitstoday->{hits} hits today};
my ($rv, $sth) = $S->db_select({
WHAT => 'sum(hits) as hits',
FROM => 'hits'});
my $hitstodate = $sth->fetchrow_hashref();
$content .= qq{, $hitstodate->{hits} hits since we started counting...};
return {content => $content};
And that's really it. For my site, I embedded this into the header for all pages, and used a blank box template (just make a block that only contains |content| and name it empty_box). When I upgraded to CVS the other day, I found that executing boxes inside of included blocks (like the header block) was kind of iffy, so I have since moved the header code into each of the templates themselves...I only mention this if you run into this problem yourself.
If you would like to see what this looks like in action, just go to my site - its on every page. |
|
Story Views
|
12 Scoop users have viewed this story.
|
|