Jump to content

Paging a list (divide to separate pages)


etrader

Recommended Posts

<?php

//Dummy array for testing
$list_array = range(1, 500);

//Define how many records you want on a page
$records_per_page = 20;

//Cacluate total records and total pages
$total_records = count($list_array);
$total_pages = ceil($total_records/$records_per_page);

//Get/define current page
$current_page = (int) $_GET['page'];
if($current_page<1 || $current_page>$total_pages)
{
    $current_page = 1;
}

//Get records for the current page
$records = array_splice($list_array, ($current_page-1)*$records_per_page, $records_per_page);

//Create ouput for the records of the current page
$list_ouput = '';
foreach($records as $value)
{
    $list_ouput .= "<li>{$value}</li>\n";
}

//Create pagination links
$first = "First";
$prev  = "Prev";
$next  = "Next";
$last  = "Last";
if($current_page>1)
{
    $prevPage = $current_page - 1;
    $first = "<a href=\"test.php?page=1\">First</a>";
    $prev  = "<a href=\"test.php?page={$prevPage}\">Prev</a>";
}
if($current_page<$total_pages)
{
    $nextPage = $current_page + 1;
    $next = "<a href=\"test.php?page={$nextPage}\">Next</a>";
    $last = "<a href=\"test.php?page={$total_pages}\">Last</a>";
}

?>
<html>
<body>
<h2>Here are the records for page <?php echo $current_page; ?></h2>
  <ul>
    <?php echo $list_ouput; ?>
  </ul>
Page <?php echo $current_page; ?> of <?php echo $total_pages; ?>
<br />
<?php echo "{$first} | {$prev} | {$next} | {$last}"; ?>
</body>
</html>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.