Certainly - here goes
PHP Code:
$animals = array("cat", "dog", "rat", "rabbit", "lion", "tiger", "mouse", "monkey", "fish", "fox");
This is the complete list of items (things) that you want to display, page by page
PHP Code:
$num_per_page = 3;
$max_items = 10;
$total_items = count($animals);
oops, remove the $max_items variable - it is not required.
$num_per_page - this is the number of items to be displayed on a single page.
$total_items - this is the total number of items to be displayed.
PHP Code:
// read passed in page number and validate it
if (true === isset($_GET['page']))
{
$start = intval($_GET['page']);
if ( ($start < 0) || ($total_items < $start) )
{
$start = 0;
}
}
else
{
$start = 0;
}
Ths section of code is used to retrieve the page number from the link ($_GET['page']) which is then stored in $start.
$start is then checked to make sure that is is between the first and last item in the array. Why? becase you don't want to display non-existent items.
PHP Code:
// calcualte start and end ponits in array
$start *= $num_per_page;
$end = $start + $num_per_page;
if ($total_items < $end)
{
$end = $total_items;
}
This section of code calculates the start position in the array i.e the first item that you want to display on the selcted page, and also the last item to be displayed, so that you don;t display non-existent items.
PHP Code:
// Display the data
for ($i = $start; $i < $end; $i++)
{
echo 'Animal at offset ' . $i . ' is ' . $animals[$i] . '<br />';
}
This section of code actually displays the data, 1 items per line.
PHP Code:
// build links
$link_start = '<a href="' . $_SERVER['PHP_SELF'] . '?page=';
$link_end = '</a>';
This section of code just creates some variables to be used when generating the links
PHP Code:
$num_pages = ceil($total_items / $num_per_page);
Calculate the total number of pages to generate links for. ceil returns the next highest valus of the passed in variable, roundng up where necessary
PHP Code:
for ($i = 0; $i < $num_pages; $i++)
{
echo $link_start . $i . '">Page ' . $i . $link_end . ' ';
}
This section of codes generates and displays the page links
So
Page 0 displays animals 0 to 2
Page 1 displays animals 3 to 5
Page 2 displays animals 6 to 8
Page 3 displays animals 9 to 10
I hope this explains things in more detail.
Run this code and then do a 'Vie Source' to see what the links look like.
Don't hesitate to ask more questions if I have glossed over anything.
Bookmarks