The attentive among you might have noticed a new “Random” link at the bottom of each post in this blog, taking you to a (you guessed it) random post on this blog, powered by the RANDOM()
function of SQLite (because, you do remember that the search feature in this blog is built on top of SQLite, do you?)
The implementation is as simple and boring as one might expect. It is also quite fast. Maybe it could be made even simpler and more boring. Simple and boring is good.
<?php
declare(strict_types=1);
// Open SQLite in readonly mode
$path = realpath(__DIR__ . 'data.db');
$access = [PDO::SQLITE_ATTR_OPEN_FLAGS => PDO::SQLITE_OPEN_READONLY];
$db = new PDO('sqlite:' . $path, null, null, $access);
// Query the database for a random entry
$sql = "SELECT path FROM articles ORDER BY RANDOM() LIMIT 1;";
$select = $db->prepare($sql);
$select->execute();
$result = $select->fetchAll(PDO::FETCH_ASSOC);
$url = $result[0]['path'];
// Redirect the user
header('Location: '. $url);
die();
You can try the feature clicking here, and I’ve added the same to De Programmatica Ipsum because reasons.