I just finished my first pagination script the other day. It wasn't that hard. Honestly I would be happy to help you understand the logic of it but I am not going to code it for you - I also believe this topic has been covered on these boards and this is a possible duplicate.
How much PHP do you know? The logic behind your pagination script (assuming the data is coming from a database) is something like this:
You need at least 2 database queries
-Your first query will tell you how many results there are and your second query will actually provide the results.
There are a few variables you will need - You will need to know the number of items. You will also need to know the limit - that is, how many items can appear on each page. You find the number of pages by dividing the limit from the number of items (# of items / limit per page )
The Display HTML - To create the HTML of the pagination I used a series of if statements. Kind of like the following pseudo code:
if ( isset( $_GET['page'] ) ) {
$page = preg_replace( '/[^0-9]/', '', $_GET['page'] );
}
else {
$page = 1;
}
/* the following code will not work
with the identity (===) operator
because when coming from get $page
is a string not an int */
if ( $current_page == 1 ) {
$page2 = $page + 1;
$page3 = $page + 2;
$page4 = $page + 3;
$pagination .= "<div>Pg $page</div>";
// if theres a second page, display page 2
if ( $num_of_posts > ( $limit * 1 ) ) {
$pagination .= "<a>$page2 ></a>";
}
// if there is a 3rd page
if ( $num_of_posts > ( $limit * 2 ) ) {
$pagination .= "<a>$page3 ></a>";
}
// if there is a 4th page
if ( $num_of_posts > ( $limit * 3 ) ) {
$pagination .= "<a>$page4 ></a>";
}
// if there is more than 4 pages
if ( ($page4 != $last_page && $page3 != $last_page ) {
$pagination .= "<a href='" . $last_page . "'>> ></a>";
}
}
This process will need to be repeated. How much you repeat it is entirely up to you. You can rewrite the if / elseif statements as a switch statement, I personally do not use the switch statement in web programming.
You can take the same approach to ( $page == 2 ), ( $page == $last_page ), ( $page == ( $last_page - 1 ). You can go overboard. This simply ensures that the HTML output will be appropriate if there is only one or two pages of content.
The Second Query - The second query will fetch the results from the database. The limit will be ( ( $page - 1 ) * $limit_per_page ), $limit_per_page
ie:
$limit = ( $page - 1) * $limit_per_page
$sql= "SELECT post, user, id, etc, whatever
FROM table
WHERE this = that
ORDER BY foobarz ASC[/DESC]
LIMIT ".$limit.",".$limit_per_page;
I hope this explains it enough for you to build it! Good luck! Let me know if you need any more explaining!