http://www.phpbuilder.com/columns/white-eisenhamer20060914.php3
An interesting article on how to achieve pagination, the example uses a sample alphabet data set i.e a-z and places it in an
array_chunk()
. I'm having trouble converting the same code into one that uses a database result set.
This is the current code from the article:
<?php
// First of all, handle configuration ... Read in values from a GET
// and default values that don't exist:
$page = (isset($_GET['page']) && ($_GET['page'] > 0))
? intval($_GET['page']) : 1;
$view = (isset($_GET['view']) && ($_GET['view'] > 0))
? intval($_GET['view']) : 10;
// Create our fake data to paginate on, just use the alphabet
$data = range('a', 'z');
// Now, chunk the data into equal sized pieces, based upon the view.
$pages = array_chunk($data, $view, true);
// Now output the chunk of data that was asked for:
echo "<p>The results are:</p>\n<p>\n";
foreach($pages[$page - 1] as $num => $datum) {
echo $num + 1, ". {$datum}<br />\n";
}
echo "</p>\n";
// Now create the options to change what page you are viewing:
echo '<p>Switch to page: |';
$get = $_GET;
foreach(range(1, count($pages)) as $p) {
// If this is the current page:
if ($page == $p) {
echo " {$p} |";
} else {
// We need to give them their option - First generate the URL needed
// We want to duplicate any query string given to us, but replacing
// any pagination values with our new page. Easiest is to take a
// current copy of get, update it for our values, then recreate it.
$get['page'] = $p;
$query = http_build_query($get);
echo " <a href=\"{$_SERVER['PHP_SELF']}?{$query}\">{$p}</a> |";
}
}
echo "</p>\n";
// Now let's give some options to change how many results we see per page:
$options = array(3, 5, 10, 50);
// Make a new copy of the $_GET array to play with again
$get = $_GET;
// Always set page to 1 when making a change to the number of results:
unset($get['page']);
// And let's output the options in the same manner as the pages:
echo '<p>Results per page: |';
foreach($options as $o) {
// If the current option:
if ($o == $view) {
echo " {$o} |";
} else {
// Give the new option, again by regenerating the GET
$get['view'] = $o;
$query = http_build_query($get);
echo " <a href=\"{$_SERVER['PHP_SELF']}?{$query}\">{$o}</a> |";
}
}
echo "</p>\n";
?>
Any help from you guys would be appreciated...
Cheers