How would one do that?
I have a table called posts
which contains the all the posts for certain topics where I show 10 posts per page.
So I got these tables:
id | title
8976 | Determine which page a post is in
and a posts table
id | author | message | topic_id
1 | jim | bla bla | 8976
2 | jake | bla bla | 8976
3 | bob | bla bla | 8976
4 | rob | bla bla | 8976
5 | john | bla bla | 8976
6 | aron | bla bla | 8976
7 | eric | bla bla | 8976
8 | brad | bla bla | 8976
9 | ken | bla bla | 8976
10 | james | bla bla | 8976
11 | dan | bla bla | 8976
12 | stan | bla bla | 8976
13 | nick | bla bla | 8976
14 | justin | bla bla | 8976
15 | steve | bla bla | 8976
16 | mark | bla bla | 8976
17 | billy | bla bla | 8976
18 | harry | bla bla | 8976
19 | david | bla bla | 8976
20 | brian | bla bla | 8976
Why do I wanna do this? To redirect the user to the post they edited. Now if it's on another page then first page, well yeah they wont get redirected to it.
and I'm not gonna use a pre made forum. Im just making this for learning and fun and it will probably never go live.
I know how to count and get the numbers of rows, but then figure out what page it is on I have no idea. I'm terrible at math, and I really mean terrible. So please help me in the right direction.
Right now I'm using:
$test = $db->query("SELECT COUNT(*) FROM posts WHERE topic_id = $topic_id AND id <= $id")->fetchColumn();
echo "Post is located on page: ".$test[0];
Does work, but the 2 last posts on EVERY page gets current page + 1 :/
and if theres lets say one post on the last page, it says its on page 1
Here is a mySQL solution to fetch the page number of the post with id=19
. I'm considering 10 itens per page.
SELECT FLOOR(COUNT(id)/10) + 1
FROM posts
WHERE id < 19
Assuming you are displaying the posts ordered by the id, you can do this:
SELECT COUNT(*) FROM posts WHERE topic_id = 8976 AND id <= 15
This will give you the position of the post with the id 15 for example. Now you can check what page this position is on:
$page = floor($position / 10);
So in this example, post 15 is on page 2.