Advertisement
framp

PHP Pagination

Oct 11th, 2012
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.92 KB | None | 0 0
  1. <?php
  2. //Inizializzo il seed per generare i numeri casuali in modo
  3. //che ogni esecuzione dello script dia risultati uguali
  4. srand(17642139112);
  5.  
  6. //Uso un array come se fosse una tabella MYSQL
  7. //E la popolo con dati casuali
  8. $data = array();
  9. for ($i=0; $i<739; $i++)   
  10.     $data[$i] = rand(0, 100000);
  11.  
  12.  
  13. //Numero di pagina corrente
  14. $currentPage = $_GET['page'] ? $_GET['page'] : 1;
  15.  
  16. //Elementi per pagina
  17. $maxElementsPerPage = 13;
  18. //Massimo numero di pagine nella paginazione
  19. $maxPagesInPagination = 10;
  20. //Mostro il 70% di $maxPagesInPagination nelle prime pagine
  21. $firstPagesInPagination = floor($maxPagesInPagination/100*70);
  22. //Il restante nelle ultime
  23. $lastPagesInPagination = ($maxPagesInPagination-$firstPagesInPagination);
  24.  
  25. //Equivalente a COUNT(*)
  26. $dataLength = count($data);
  27. $pagesNumber = ceil($dataLength/$maxElementsPerPage);  
  28.  
  29. //Equivalente di un SELECT con LIMIT appropriato
  30. $data = array_slice($data, ($currentPage-1)*$maxElementsPerPage, $maxElementsPerPage);
  31. //Stampo la tabella
  32. ?>
  33. <table>
  34.     <?php foreach ($data as $k => $v){ ?>
  35.         <tr>
  36.             <td><?php echo $k+1; ?></td>
  37.             <td><?php echo $v; ?></td>
  38.         </tr>
  39.     <?php } ?>
  40. </table>
  41.  
  42. <div class="navigation">
  43. <?php
  44.  
  45. //Stampo la barra di navigazione con i links alle altre pagine
  46.  
  47. //Pagina precedente
  48. if ($currentPage!=1){ ?>
  49.     <a href="?page=<?php echo $currentPage-1; ?>">&lt;&lt;</a>
  50. <?php }
  51.  
  52. //Tutte le pagine
  53. $counter = 0;
  54. for ($i=1; $i<=$pagesNumber; $i++){
  55.     if ($counter<$firstPagesInPagination){
  56.         if ($i==$currentPage){ ?><strong><?php }
  57.         ?><a href="?page=<?php echo $i; ?>"><?php echo $i; ?></a> <?php
  58.         if ($i==$currentPage){ ?></strong><?php }
  59.     }else{
  60.         ?> ... <?php
  61.         $i = $pagesNumber-$lastPagesInPagination;
  62.         $counter = $firstPagesInPagination-$lastPagesInPagination-1;
  63.     }
  64.     $counter++;
  65. }
  66.  
  67. //Pagina successiva
  68. if ($currentPage!=$pagesNumber){ ?>
  69.     <a href="?page=<?php echo $currentPage+1; ?>">&gt;&gt;</a>
  70. <?php }
  71. ?>
  72. </div>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement