Friday, August 1, 2014

Paginated Table From Text File

<?php
function paginate($display, $pg, $total) {

$display = 20; // how many records per page?
$filename = 'path_to_File.txt';
$data = file($filename);
$total = count($data);

  /* make sure pagination doesn't interfere with other query 
string variables */
  if(isset($_SERVER['QUERY_STRING']) && trim(
    $_SERVER['QUERY_STRING']) != '') {
    if(stristr($_SERVER['QUERY_STRING'], 'pg='))
      $query_str = '?'.preg_replace('/pg=d+/', 'pg=', 
        $_SERVER['QUERY_STRING']);
    else
      $query_str = '?'.$_SERVER['QUERY_STRING'].'&pg=';
  } else
    $query_str = '?pg=';
    
  /* find out how many pages we have */
  $pages = ($total <= $display) ? 1 : ceil($total / $display);

$last = $total/$display;
    
  /* create the links */
  $first = '<a href="'.$_SERVER['PHP_SELF'].'?pg=1"> <<
</a>';

$prevpg = $pg-1;
  $prev = '<a href="'.$_SERVER['PHP_SELF'].  '?pg=' .$prevpg. '">
< </a>';
$nextpg = $pg+1;
  $next = '<a href="'.$_SERVER['PHP_SELF'].'?pg=' .$nextpg.'">
></a>';
  $last = '<a href="'.$_SERVER['PHP_SELF'].$query_str.$pages.'">
>> </a>';
   
  /* display opening navigation */
  echo '<div><p align="center">';
  echo ($pg > 1) ? "$first : $prev :" : '<< : < :';
  
  /* limit the number of page links displayed */
  $begin = $pg - 4;
  while($begin < 1)
    $begin++;
  $end = $pg + 4;
  while($end > $pages)
    $end--;
  for($i=$begin; $i<=$end; $i++)
    echo ($i == $pg) ? ' ['.$i.'] ' : ' <a href="'.
      $_SERVER['PHP_SELF']. '?pg='.$i.'">'.$i.'</a> ';
    
  /* display ending navigation */
  echo ($pg < $pages) ? ": $next : $last" : ': > : >> ';
  echo '</p></div>';
}
 
/* set pagination variables */
$display = 20;
$pg = (isset($_REQUEST['pg']) && ctype_digit($_REQUEST['pg'])) ?
  $_REQUEST['pg'] : 1;
$start = $display * $pg - $display;
 
?>

No comments:

Post a Comment