0

I'm rather new to PHP and coding, I have my index.php displaying the last 20 blog posts submitted into my database. How would I create pagination so that it would only display 10 posts at a time, with a next a previous button to view another 10 posts?

<ol>
  <?php

    $link = mysqli_connect( 'localhost', 'BlogDB', 'password'  );
    mysqli_select_db( $link, 'BlogDB' );

    $results = mysqli_query( $link, 'SELECT * FROM Blog ' );

    $resultsArr = array();
      while( $record = mysqli_fetch_assoc( $results ) ) {
        $title = $record['title'];
        $email = $record['email'];
        $post = $record['post'];

        array_push( $resultsArr, "<li>$title <br> $email <br>$post</li>");
    }

    mysqli_free_result( $results );


    for ($i = count($resultsArr); $i > 0; $i--) {
      if ($i >= count($resultsArr) - 10) {
        print $resultsArr[$i];
      }
    }
  ?>
</ol>
Scott Weldon
  • 9,673
  • 6
  • 48
  • 67
My_Bynard
  • 1
  • 1
  • 3
    http://stackoverflow.com/questions/3705318/simple-php-pagination-script/3707457#3707457 – Fabio Dec 02 '16 at 22:23

1 Answers1

0

To paginate the results of a query :

You must make a function that takes as input: $numberPerPage, $pageNumber

Let's make a Hand execution

For example: $numberPerPage = 10; And $pageNumber = 3

We define the post from which to start the list : ($PageNumber-1)*$numberPerPage => (3-1)*10 = 20

And the number of posts to display => $numberPerPage = 10

So the request is going to be like this

SELECT * FROM Blog LIMIT 10 OFFSET 20;

=> Return only 10 posts, start on record 21 (OFFSET 20)

Finally for the view: You must know the total number of pages to make links to the page: For this, it's necessary to know the total number of posts then divide it by $numberPerPage !

this is an example to show links to pages:

for ($i = 1; $i <= $totalPageNumber; $i++)
echo "<a href='index.php?page=".$i."'>".$i."</a>";

In index.php get with $_GET ['page'] the page number and call the function that will get the corresponding posts that will use the sql query above.

I hope you have understood my idea :)

ZakSdn
  • 1
  • 3