The posts in my forum all have an individual permalink.
The posts are paginated and the users can sort them by date and rating.
When a permalink is accessed, the page the post resides on needs to be calculated due to the pagination.
The posts are stored with an auto incrementing id in a mysql innodb table.
At the moment I use the following for the calculation when the posts are sorted by their score (rating):
<?php
// These variables originate from the corresponding uri segments
// For example: http://domain.tld/topics/[ID]/[SLUG]/[POST_ID]
$post_id = $uri->segment(4);
$topic_id = $uri->segment(2);
$post_per_page = 10;
$query = $db->query('SELECT id FROM topic_posts WHERE topic_id = ' . $topic_id . ' ORDER BY score desc');
foreach ($query as $key => $post)
{
if ($post->id == $post_id)
{
$postOnPage = ceil(($key + 1) / $post_per_page);
break;
}
}
However, the amount of posts will keep increasing and fetching all posts seems awkward.
For the date sorting I use the following query, but it's not working for the rating sorting as the post id's are then not in incrementing order:
SELECT CEIL((COUNT(*) + 1) / $posts_per_page) FROM topic_posts WHERE topic_id = $topic_id AND id < $post_id;
So... How can I avoid the php foreach loop and achieve the same with the db query?