RSS Forums RSS
Please support our PHP advertiser: Lunarpages PHP Web Hosting

Clean Previous Next Script for MySQL results

Join Date: Apr 2005
Posts: 12
Reputation: robbyd is an unknown quantity at this point 
Rep Power: 4
Solved Threads: 0
robbyd robbyd is offline Offline
Newbie Poster

Re: Clean Previous Next Script for MySQL results

  #20  
Apr 30th, 2005
Ive done alot of stuff with 'pagination' and yes using LIMIT in your sql query is the best way to go about it. Theres basically two parts to make it work.

1. is the making the sql query match the page you're on
and
2. displaying the proper pages links, like the " << prev 1 2 3 4 next >> "

[PHP]
// first get the current page ( file.php?p=1 or 2 or what ever)
if(isset($_GET['p'])) $page = $_GET['p'];
else $page = 1;
// set how many entries you want per page (for example 20)
$display = 20;

// set the LIMIT for the sql query
$start = $page * $display - $display;

// then the query should look something like
$sql = "SELECT ... FROM table WHERE ... LIMIT $start, $display";

// The LIMIT should go at the very end of the query.
[/PHP]

so the first page will display entries starting at 0, showing 20 entries.
page 2 will start at entry #20 and display the next 20 and ect..


The second part is showing the 'next, prev' links

[PHP]
// first you need a query to find how many entries there are total in the database
// I use the count function for this
$sql = "SELECT COUNT(*) AS total FROM table_name";
$total = mysql_result(mysql_query($sql),0,'total');

// then break up the total into pages
$totalpages = $total / $display; // in this case $display = 20
// round up on pages
$totalpages = ceil($totalpages);



// if its not page 1, display a 'prev' link

if($page != 1) {
$prev = $page--;
echo '<a href="'. $PHP_SELF . '?p=' . $prev . '">prev</a>';
}

// set current page for loop
$current = 1;

// use while function to loop through each page and display link

while ($current <= $totalpages) {
if($current == $page) echo $currentpage;
else echo '<a href="'. $PHP_SELF . '?p=' . $currentpage . '">' . $currentpage . '</a>';
$current++;
}
// if current page is not the last page, display 'next' link

if($page != $totalpages) {
$next = $page++;
echo '<a href="'. $PHP_SELF . '?p=' . $next . '">next</a>';
}


[/PHP]


And thats all there is to it. If anyone has questions about this, let me know.
Reply With Quote  
Forums | Blogs | Tutorials | Code Snippets | Whitepapers | RSS Feeds | Advertising
All times are GMT -4. The time now is 4:02 am.
Newsletter Archive - Sitemap - Privacy Statement - Acceptable Use Policy - Contact Us
Forum system based on vBulletin Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
©2003 - 2008 DaniWeb® LLC