-3

I'm new to PHP and I'd like to add a pagination function to the page.

I have this piece of code:

$result = mysql_query( "select title from post LIMIT 5 OFFSET 0");
while ($row = mysql_fetch_object($result)) {
    echo $row->title;
}

I'd like to show only five post titles per page. If I want to add a pager to this page, how do I do this? E.g: the URL is example.com/post.html.

1

2 Answers 2

1

You can use a parameter in the query string that indicates the page that you are looking.

So for example: example.com/post.html?page=2 means that someone clicked on the link to the second page.

And then in your code you can do something like this:

$rowsPerPage = 5;
$page = isset($_GET['page']) ? $_GET['page'] : '0';
$index = $page * $rowsPerPage;
$result = mysql_query( 'select title from post LIMIT ' . $index . ', ' . $rowsPerPage);
while ($row = mysql_fetch_object($result)) {
   echo $row->title;
}

Also you need get the total quantity of records that you have in order to print the pagination links. You can use a SELECT COUNT(*) FROM POST to get the total of rows. Then you have to calculate how many pages you will show.

Hope this helps you

1
  • if the total quantity of records is $total, how do i do?
    – learn1208
    Dec 8, 2012 at 12:38
0

you simply need to make the offset dynamic, so the first page is 0, the second 5, the third 10, etc. you can use a GET protocol to send the offset to the URL with each pagination:

<a href="example.com/post.html?offset=0">1</a>
<a href="example.com/post.html?offset=5">2</a>
<a href="example.com/post.html?offset=10">3</a>

obviously you generate the pagination links dynamically with a for loop, the formula being (OFFSET= (num_pag-1) * LIMIT)

then you PHP would be:

$offset = $_GET['offset'];
$result = mysql_query( "select title from post LIMIT 5 OFFSET $offset");
1
  • OFFSET= (num_pag-1) * LIMIT what's these meaning. thank you. if the total rows = $total.
    – learn1208
    Dec 8, 2012 at 13:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.