Post by Jacob on Jun 12, 2009 14:36:12 GMT -5
If you are going to have a site where users can submit stuff, and the stuff is listed on one page, you definitely need pagination. This pagination script consists of two main parts: getting the correct records and displaying them, and displaying the page links at the bottom.
First, our data. We will use arrays in this example, but you can adapt it for MySQL.
Next, figure out which posts need to be shown, and cut off the rest.
Now that the data is paginated correctly, we can output it (this code will need to be replaced with your own.)
The last step is to show the next page/previous page links.
And we’re done! When a user clicks the links at the bottom, $start is added to or subtracted from. If $_GET['start'] is not set (the user has just entered this site area and hasn’t changed the page yet) it is set to 0, so the script will show the posts starting at the beginning.
First, our data. We will use arrays in this example, but you can adapt it for MySQL.
<?php
$data = array(
1 => array('user' => 'Bob', 'comment' => 'I like your site!'),
2 => array('user' => 'George', 'comment' => 'I like your site more than he does!'),
3 => array('user' => 'Tom', 'comment' => 'I like your site, but mine\'s better.'),
4 => array('user' => 'Alex', 'comment' => 'This site is awful. Mine is MUCH better.'),
5 => array('user' => 'Admin', 'comment' => 'Stop insulting my site!! I made $25,000 last month!!!'),
6 => array('user' => 'Harry', 'comment' => 'Woof!'),
);
Next, figure out which posts need to be shown, and cut off the rest.
$perpage = 2; //Obviously you would want to change this to something higher, depending on the content.
if(isset($_GET['start'])) $start = $_GET['start']; else $start = 0;
$numposts = count($data);
$data = array_slice($data, $start, $perpage);
Now that the data is paginated correctly, we can output it (this code will need to be replaced with your own.)
foreach($data as $k => $v)
{
echo $data[$k]['user'].' said: '.$data[$k]['comment'].'<br/>'."\n";
}
The last step is to show the next page/previous page links.
if($start > 0)
{
$text .= '<a href="guestbook.php?start='.($start - $perpage).'">< Previous Page </a>';
}
if($start > 0 && $numposts > $perpage && $start < $numposts - $perpage)
{
$text .= ' | ';
}
if($numposts > $perpage && $start < $numposts - $perpage)
{
$text .= '<a href="guestbook.php?start='.($start + $perpage).'">Next Page ></a>';
}
echo $text;
And we’re done! When a user clicks the links at the bottom, $start is added to or subtracted from. If $_GET['start'] is not set (the user has just entered this site area and hasn’t changed the page yet) it is set to 0, so the script will show the posts starting at the beginning.