Random entry

 | Perl | 0 Comments

For many many months now, the random link at the top of this page just below the banner hasn't been working. I decided to fix it once and for all.

First of all I redefined the link to refer to a new CGI script mt_random.pl which I wrote myself using good old Perl. Here is how the new link is defined:

<a href="/cgi-bin/mt_random.pl?blog_id=1" title="Jump to a completely random place on this blog...">Random</a>

Of course the whole random magic of the situation is the Perl script mt_random.pl itself, which looks like this:

#!/usr/bin/perl -w
use DBI;
use CGI;
use strict;

my $q = new CGI;

my $format_url = "http://www.kiffinsblog.com/archives/%d/%0.2d/%s.html";

my $hostname = 'localhost';
my $database_name = 'db_name';
my $user = 'db_usr';
my $password = 'db_password';

my $dsn = "dbi:mysql:database=$database_name;host=$hostname";

my $blog_id = $q->param('blog_id') || 1;

my $dbh = DBI->connect($dsn, $user, $password) or die "Can't connect to $dsn: $DBI::errstr";

my $sql = <<EOF;
SELECT
  entry_basename,
  entry_title,
  date_format( entry_created_on, '%Y' ) AS entry_year,
  date_format( entry_created_on, '%m' ) AS entry_month
FROM
  mt_entry,
  mt_author
WHERE
  entry_blog_id = $blog_id
AND
  entry_status = 2
AND
  author_id = entry_author_id
ORDER BY rand( )
LIMIT 1
EOF

my $sth = $dbh->prepare($sql);
$sth->execute();

my $ref = $sth->fetchrow_hashref;

print $q->redirect(sprintf($format_url, $ref->{entry_year}, $ref->{entry_month}, $ref->{entry_basename}));

You can now try it out yourself by clicking on the link above, and if you cannot find it then clicking here.

Pretty amazingly magical don't you think?

Leave a comment

Recent Entries

No more winter greens
The cool, windy and grayish afternoon calls me onward. It's drizzling on my windshield but I do not care.
Champion of Scotland
I nearly cried my eyes out when I discovered that young Tommy Morris dies in the prime of his
Sticky keyboard
Up until yesterday the Del-, Ins- and Home- keys on the upper right-hand corner were sticking alot, and it's
Perl on steroids
Read this from beginning to end, and you then tell me with a straight face that it hasn't completely
Seventh Dutch Perl Workshop
Going to attend the 7th Dutch Perl Workshop tomorrow in Arnhem. Cannot wait to get up bright and early