You can use the LIMIT and OFFSET parts of a query to select subsets of an entire result set. Keep in mind that a database is just a set of data -- there's no guarantee of any sort order unless you specify one in your query.
As such, you can figure out the total number of rows in the result set:
$count = query("SELECT COUNT(*) FROM ....");
Dividing this number by the number of records per page will give you the number of pages you need:
$num_pages = ceil($count / $rows_per_page);
We use the ceil() function because you'll need a new page for the last few rows. For example, if you have 25 rows, and display 10 rows per page, 2.5 doesn't make sense for "num_pages", but 3 does.
Now, you can select subsets of the data based on what page you're currently viewing. Assume the page number starts with 1. (In our 25 rows example, we'll have pages 1, 2, and 3). We use the page number and rows_per_page to calculate the offset for our query:
$offset = ($page_number - 1) * $rows_per_page;
We use ($page_number - 1) because the first page displays rows 0 - 9, not rows 1 - 10.
$result = query("SELECT * FROM table ORDER BY x LIMIT $rows_per_page OFFSET $offset");
Hope this gives you an idea of how to do this.
Generating page number links is easy -- once you know how many pages of results there are, you just generate a link for each one:
$links = array();
for ($i = 1; $i <= $num_pages; ++$i)
{
if ($page_number !== $i) // where $page_number is the currently viewed page
{
$links[] = "<a href=\"{$_SERVER['PHP_SELF']}?page_number={$i}\">{$i}</a>";
}
else
{
$links[] = "{$i}";
}
}
echo join(" | ", $links);
Next and Previous links are easy, too.
if ($i == 1)
{
$prev = "Prev"; // first page, no previous page. Don't create link.
}
else
{
$prev = "<a href=\"{$_SERVER['PHP_SELF']}?page_number=" . ($i - 1) . "\">Prev</a>";
}
if ($i == $num_pages)
{
$next = "Next"; // last page, no next page. Don't create link.
}
else
{
$next = "<a href=\"{$_SERVER['PHP_SELF']}?page_number=" . ($i + 1) . "\">Next</a>";
}
echo "{$prev} | {$next}";
Take care,
Nik
http://www.bigaction.org/