I’m developing a blog system with php and mysql with the following db structure:
Article
-id
-firstMessage
-lastMessage
-body
Comment
- id
- article_id
- publiched_date
- body
The idea here is make use of pagination, where the article with a lot of comments shows a link tree like [first][1][2][3][last], 10 comments by page. Everything goes fine, I have create a nice sql that select 10 messages according to the page number by url:
example.com/?article=3&page=2
Where is the ploblem? Well, supponse that I have this url in my homepage:
example.com/?article=3&message=3565
According to the url above, How can I determinate the page number where this message is? Do you have any idea to guide me to the right direction?
Edit
- The messages ids are not consecutives, for example, an article could have the comments: 125, 364, 561, 1522
Basically, select the comments from the same article, sorted by ID (or another column if the
idcan be out of order–non-consecutive is fine), and do a little math with the result. Here’s the code (demo):Simply plug in the comment ID and article ID where the
?are (or, even better, use this exact code in a prepared statement). If you change the number of comments per page, make sure you change the10in the query as well.For this query, you just need an index on
article_id(and aPRIMARYindex onid).