Benjamin Lu

everyday is cool

A Small Blog Database

A folder of HTML pages is easy to browse until you want to show the most recent five entries automatically. A database can answer that question without you updating the index every time you add a page.

In a local database, make a sample posts table with an integer id, a text title, and a published_at column. Add a few example rows, including two with the same date. Then run:

SELECT id, title, published_at
FROM posts
ORDER BY published_at DESC, id DESC
LIMIT 5;

Check the order, add a newer post, and run the query again. The new row should appear first. The second sort key keeps the order predictable when dates match. This is the part of a blog engine that turns saved entries into a list. The application still needs to escape the titles when it puts them into HTML and use parameters when a query takes user input.