0
votes

there is a function for showing posts (pleas ignore syntax errors )

function get_all_posts ($offset = 0 )
{
  $q =  $db->query("select * from tbl limit 10 offset $offset ");
  $template->load_view('posts' , $q ); 
}

now lets say i have function called get_one_post with a single post offset and total posts count as argument

function get_one_post($requested_post_offset = 0 , $totl_posts_count = 0 )
{

}

basically what i want to do in this get_one_post is to calculate page offset of requested_post and call get_all_posts function , so it show the page that contains that specific post

function get_one_post($requested_post_offset = 0 , $totl_posts_count = 0 )
{
   $page_offset = // calculation( $requested_post_offset , $totl_posts_count );
   get_all_posts ($page_offset);

}

i can say

 get_all_posts ($requested_post_offset );

but it shows requested post as first post in the page ... but i wan to be in it's natural place in the pagination not the first one

how should i do the calculation part ?

---------------------------------EDIT----------------------------

please note that i know how to create and implement pagination ... that's not the issue here my framework pagination system works with offsets instead of page numbers .. like if per_page is 10 , pagination links would be like

page 1  => page.php?offset=0
page 2  => page.php?offset=10
page 3  => page.php?offset=20

in this example if the $requested_post_offset is 15 then THE PAGE OFFSET IS 10 and i should get the result of

page 2  => page.php?offset=10
2
Well the first thing you must understand in most pagination implementations is the total number of records in the table. Do you have an initial query to determine the row count?Mike Brant
@MikeBrant i get that in the second argument of get_one_post functionmax

2 Answers

0
votes

If there are m posts per page, the post k will be on page ceil(k/m). For example, if you put 25 posts per page, the post 86 will be on page ceil(86/25) = 4.

The offset of the post on the page would be k%m, where the position of the first is 0 and of the last m-1. For example, 86%25 = 11 so the post 86 would be the 12th on the page.

0
votes

Here are some general formulas typically used in pagination:

total_pages = ceil(row_count / row_limit_per_page)
page_at_offset = ceil((zero_based_offset + 1) / row_limit_per_page))
zero_based_offset_for_a_given_page = (page_at_offset - 1) * row_limit_per_page

Note that here I am treating page numbers as starting with 1.

If your inputs are zero_based_offset (the zero-based offset of the row you are interested in) and the row_limit_per_page then you simply need to to use the last two equations. The first equation is typically used for display purposes (when you need to show the total number of pages for navigation or the like).