Friday, February 13, 2009

Pagination Code

Welcome to the Darkstar Media Blog.

Here is a nifty piece of code I wrote last week for php pagination. What is "pagination" you might ask.  For me, it is a system of numbering pages for searching and displaying database results which are too much to display on one page. Basically, you break it up into multiple pages.


$id = $_GET['id']; // this is a variable unrelated to the paging, but used for the data display
$whichpage = $_GET['whichpage']; // this tells us which page we are on

// checking to see what page we are on and what results we should display
if(!$_GET['whichpage']) {
$thepage = 0; 
$thepage_final = 0;
} else {
$thepage = $_GET['whichpage'];
$thepage_final = $thepage - 1; 
}

$number_per_page = 6; // how many results we should display per page
$startnumber = $thepage_final * $number_per_page; // which number to start the new record display from

// recordset to display results
mysql_select_db($database_mine, $mine);
$query_Recordset_shoelist = "SELECT * FROM shoes WHERE shoes_cat = $id ORDER BY shoes_name ASC LIMIT $startnumber, $number_per_page";
$Recordset_shoelist = mysql_query($query_Recordset_shoelist, $mine) or die(mysql_error());
$totalRows_Recordset_shoelist = mysql_num_rows($Recordset_shoelist);

// recordset for paging
$query_Recordset_paging = "SELECT * FROM shoes WHERE shoes_cat = $id ORDER BY shoes_name ASC";
$Recordset_paging = mysql_query($query_Recordset_paging, $mine) or die(mysql_error());
$totalRows_Recordset_paging = mysql_num_rows($Recordset_paging);


// i round this up to have even amount of pages
$amountofpages = ceil($totalRows_Recordset_paging / $number_per_page);




// this is my display, inserted in the HTML wherever you want the page numbers to display 

$number_per_page) { ?>
PAGE:

// this is my display

$i = 1;
while ($i <= $amountofpages):

if($whichpage == $i) {
echo "" . $i. ""; 
} else {
echo "<" ' "a href=brand_list.php?id=" . $id . "&whichpage=" . $i . "&id2=" . $id2 . " class=pagelink>" . $i. "<" . "/" . "a>";
}


$i++;
endwhile;
?>


I hope this is commented well enough for someone to understand. The next post will hopefully be on art or something not so dry as PHP code.

No comments:

Post a Comment