Now that we have the query ready we need to create the navigation link so
our visitor can easily move from the first page to other pages. We simply print
the page number as a hyperlink. So when a visitor click on a page number the
script will show the entries for the specified page.
The code needed is shown below
<?php
// .... previous code
$query = "SELECT COUNT(id) AS numrows FROM guestbook";
$result = mysql_query($query) or die('Error, query failed');
$row = mysql_fetch_array($result, MYSQL_ASSOC);
$numrows = $row['numrows'];
$maxPage = ceil($numrows/$rowsPerPage);
$nextLink = '';
if($maxPage > 1)
{
$self = $_SERVER['PHP_SELF'];
$nextLink = array();
for($page = 1; $page <= $maxPage; $page++)
{
$nextLink[] = "<a href=\"$self?page=$page\">$page</a>";
}
$nextLink = "Go to page : " . implode(' »
', $nextLink);
}
include 'library/closedb.php';
?>
<table width="550" border="0" cellpadding="2"
cellspacing="0">
<tr>
<td align="right" class="text">
<?=$nextLink;?>
</td>
</tr>
</table>
<?php
}
?>
First we count the total number of entries we have ( $numrows
) then we find the maximum page numbers. To do this we just need the ceil()
function to round the number up.
For example, suppose we have 34 entries in our guestbook database and we want
to show 10 entries per page. From these numbers we know that we wil split the
result in ceil( 34 / 10) = 4 pages.
If the entries span in more than one page we do a loop to create the links.
The link will look something like this :
guestbook.php?page=3
Note that in above code we use $_SERVER['PHP_SELF']
instead of using the filename itself, guestbook.php.
This is done to save the trouble of modifying the code if someday we want to
change the filename.
We temporarily put the links in an array, $nextLink.
Once we get all the links in there we just join them all using implode().
And now our guestbook is done. Congratulations to you :-).
If you want the source code for this guestbook tutorial just click here
. The zip file contain all the files required but dont' forget
to modify library/config.php to match your own settings.
|