简体   繁体   中英

Pagination display issue with number pages

hey guys my English is not very good 'but i try to explain my self clear. i'm creating pagination and all of my code is working perfect.

The problem is, that i want to display only five numbers of pages and on click on next button i hide one and showing new one. it's looks like that.

next 12345 prev

next 23456 prev

Thank's for advice guys.

Here is my code :

 <?php

  $dbh = new PDO("mysql:host=localhost;dbname=northwind", "root", "123");


  $query = $dbh->prepare("SELECT ContactName FROM Customers");
  $query->execute();
  $numRows = $query->rowCount();


  if (isset($_GET['pn'])) {
      $pn = $_GET['pn'];
  } else {
      $pn = 1;
  }

  $startPage = 1;
  $perPage = 9;


  $lastPage = ceil($numRows / $perPage);


  if ($pn < 1) {
     $pn = 1;
  } else if ($pn > $lastPage) {
     $pn = $lastPage;
  }

  $controls = '';


   if ($pn != $lastPage) {

        $controls .= '<a id="next" href="' . $_SERVER['PHP_SELF'] . '?pn=' . ($pn + 1) . '"> next </a>';
   }


    for ($i=1; $i <= $lastPage; $i++) {

         if ($i == $pn) {
              $background = ' red;';
         } else {
              $background = ' green;';
         }

         $controls .= '<a id="page_' . $i . '" data-page="' . $i . '" class="num" style="background:' . $background . ' " href="' . $_SERVER['PHP_SELF'] . '?pn=' . $i . '"> ' . $i . '</a>';
    }

     if ($pn != $startPage) {

           $controls .= '<a href="' . $_SERVER['PHP_SELF'] . '?pn=' . ($pn - 1) . '"> prev </a>';
     }

      $controls .= "PAGE " . $pn . " of " . $lastPage ;


      $limit = "LIMIT " . ($pn-1) * $perPage . ', ' . $perPage;

      $query2 = $dbh->prepare("SELECT ContactName FROM Customers " . $limit . "");
      $query2->execute();

      $outputList = '';

      while($row = $query2->fetch(PDO::FETCH_OBJ)){ 

            $outputList .= '<h1>' . $row->ContactName . '</h1><hr />';

      } 

I would suggest you to use more easy approach.

Lets consider a page contains 25 results. That means: 1st Page range is: 1-25 2nd Page range is: 26-50 and so on..

Now when a user request page 2, we should display him the results of 25-49. this means the results of (page-1)*25 till page*25-1 = results in 25-49.

Now all we need is how to tell the SQL to take those into consideration.

SELECT ContactName FROM Customers LIMIT 25 OFFSET 25;

Will produce use the desired result.

Now all you need is just pass the requested page with pn as you already did. And print the next 1-3(whatever) next\\prev pages.

To know how many pages there are, just do another count sql query that will give you the result and divide it by 25.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM