Hi Everyone,

I have built my own forums and currently they are displayed in the order of newest posted (id DESC). What I want to do is keep this order however, if there was a topic which was created months ago that is not on the first page for example, I want that topic to become the first topic to be displayed when someone has replied to it like most forum boards such as IPB and vBulletin.

Thank you.

Dani AI

Generated

Short practical plan: keep a small "last activity" snapshot on the topics row and update it when a reply is posted so sorting and pagination stay cheap. pointed in the right direction; the rest here covers how to do it safely and efficiently and how to handle edge cases like pinned topics or hidden posts.

Add a few columns to your topics table (examples: last_post_time, last_post_id, last_post_user_id, reply_count, is_sticky). Put an index on last_post_time (or a composite index on (is_sticky, last_post_time)) so ORDER BY is_sticky DESC, last_post_time DESC is fast. Initialize last_post_time from the topic creation time so new topics sort correctly before any replies.

When inserting a reply, update the posts table and the topic row in one transaction so counts and timestamps never drift. Example pattern:

START TRANSACTION;
INSERT INTO posts (topic_id, user_id, body, created_at) VALUES (123, 45, '...', NOW());
SET @post_id = LAST_INSERT_ID();
UPDATE topics
  SET last_post_id = @post_id,
      last_post_user_id = 45,
      last_post_time = GREATEST(last_post_time, NOW()),
      reply_count = reply_count + 1
  WHERE id = 123;
COMMIT;

Notes and cautions: exclude invisible/deleted posts from bump logic (check visible flag), provide a no_bump flag if you want certain replies not to bump, and treat pinned topics separately so they remain on top. For high traffic sites cache the topic list and invalidate on bump. If data gets inconsistent, rebuild last_post_time once with a grouped MAX on posts for each topic. This approach scales much better than recomputing last activity with joins on every page load.

Recommended Answers

All 2 Replies

It seems that the easy way would be to have a "date of last activity" and use that to sort them.

Thanks, dude, really appreciate it.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.