...

View Full Version : PHP Pagination problem... please help



susanv
04-27-2011, 11:55 AM
Hello everyone,

I have an ecommerce website and I'm trying to add pagination, but I'm stuck. I'm sure this will be an easy fix for someone with more experience than me. The first page works fine, but I get an error when I click on Next. I'm at a loss as to why. Can someone please help...?

The page that gives an error:

http://www.hopefloatsdesign.co.za/shopping/list.php?category=clothing&subcategory=hats

Here is my code:

// Connect to the MySQL database
include "storescripts/connect_to_mysql.php";
$sql = mysql_query("SELECT * FROM products WHERE subcategory='$subcategory'");

// Adam's Pagination Logic
$nr = mysql_num_rows($sql); // Get total of Num rows from the database query
if (isset($_GET['pn'])) { // Get pn from URL vars if it is present
$pn = preg_replace('#[^0-9]#i', '', $_GET['pn']); // filter everything but numbers
} else { // If the pn URL variable is not present force it to be value of page number 1
$pn = 1;
}

//This is where we set how many database items to show on each page
$itemsPerPage = 6;

// Get the value of the last page in the pagination result set
$lastPage = ceil($nr / $itemsPerPage);
// Be sure URL variable $pn(page number) is no lower than page 1 and no higher than $lastpage
if ($pn < 1) { // If it is less than 1
$pn = 1; // force if to be 1
} else if ($pn > $lastPage) { // if it is greater than $lastpage
$pn = $lastPage; // force it to be $lastpage's value
}
// This creates the numbers to click in between the next and back buttons
// This section is explained well in the video that accompanies this script
$centerPages = "";
$sub1 = $pn - 1;
$sub2 = $pn - 2;
$add1 = $pn + 1;
$add2 = $pn + 2;
if ($pn == 1) {
$centerPages .= '&nbsp; <span class="pagNumActive">' . $pn . '</span> &nbsp;';
$centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add1 . '">' . $add1 . '</a> &nbsp;';
} else if ($pn == $lastPage) {
$centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub1 . '">' . $sub1 . '</a> &nbsp;';
$centerPages .= '&nbsp; <span class="pagNumActive">' . $pn . '</span> &nbsp;';
} else if ($pn > 2 && $pn < ($lastPage - 1)) {
$centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub2 . '">' . $sub2 . '</a> &nbsp;';
$centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub1 . '">' . $sub1 . '</a> &nbsp;';
$centerPages .= '&nbsp; <span class="pagNumActive">' . $pn . '</span> &nbsp;';
$centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add1 . '">' . $add1 . '</a> &nbsp;';
$centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add2 . '">' . $add2 . '</a> &nbsp;';
} else if ($pn > 1 && $pn < $lastPage) {
$centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub1 . '">' . $sub1 . '</a> &nbsp;';
$centerPages .= '&nbsp; <span class="pagNumActive">' . $pn . '</span> &nbsp;';
$centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add1 . '">' . $add1 . '</a> &nbsp;';
}
// This line sets the "LIMIT" range
$limit = 'LIMIT ' .($pn - 1) * $itemsPerPage .',' .$itemsPerPage;
// Now we are going to run the same query as above but this time add $limit onto the end of the SQL syntax
// $sql2 is what we will use to fuel our while loop statement below
$sql2 = mysql_query("SELECT * FROM products WHERE subcategory='$subcategory' $limit");
// END Adam's Pagination Logic
// Adam's Pagination Display Setup
$paginationDisplay = ""; // Initialize the pagination output variable
// This code runs only if the last page variable is not equal to 1
if ($lastPage != "1"){
// This shows the user what page they are on, and the total number of pages
$paginationDisplay .= 'Page <strong>' . $pn . '</strong> of ' . $lastPage. '&nbsp; &nbsp; &nbsp; ';
// If we are not on page 1 we can place the Back button
if ($pn != 1) {
$previous = $pn - 1;
$paginationDisplay .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $previous . '"> Back</a> ';
}
// Lay in the clickable numbers display here between the Back and Next links
$paginationDisplay .= '<span class="paginationNumbers">' . $centerPages . '</span>';
// If we are not on the very last page we can place the Next button
if ($pn != $lastPage) {
$nextPage = $pn + 1;
$paginationDisplay .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $nextPage . '"> Next</a> ';
}
}
// END Adam's Pagination Display Setup

$dynamicList = "";
$productCount = mysql_num_rows($sql); // count the output amount
if ($productCount > 0) {
// get all the product details
while($row = mysql_fetch_array($sql2)){
$id = $row["id"];
$product_name = $row["product_name"];
$price = $row["price"];
$details = $row["details"];
$category = $row["category"];
$subcategory = $row["subcategory"];
$date_added = strftime("%b %d, %Y", strtotime($row["date_added"]));
$dynamicList .= '<table style="float: left;" width="50%" border="0" cellspacing="0" cellpadding="6">
<tr>
<td width="17%" valign="top"><a href="product.php?id=' . $id . '"><img style="border:#666 1px solid;" src="inventory_images/' . $id . '.jpg" alt="' . $product_name . '" width="77" height="102" border="1" /></a></td>
<td width="83%" valign="top">' . $product_name . '<br />
R' . $price . '<br />
<a href="product.php?id=' . $id . '">View Product Details</a></td>
</tr>
</table>';
}
}
} else {
$dynamicList = "We have no products listed in our store yet";
}
?>

These are my divs:

<div class="box3">
<h3><?php echo $category; ?> | <?php echo $subcategory; ?></h3>
<br />
<?php echo $dynamicList; ?><br />
</div>

<div class="box2">
<?php echo $paginationDisplay; ?><br />
<br />
<h3>Total Items: <?php echo $nr; ?></h3>
</div>

bullant
04-27-2011, 12:06 PM
Maybe use this Paginator class demo as a guide.

It has page links, prev, next, first and last buttons. I've also included the sql to create the test database table the demo uses.

index.php


<?php
session_start();
//----------------------------------------------------------------------------------------------------------------------
//connect to the database
$DBUserName = "root"; //database user account name
$DBPassword = ""; //database user account password
$DBName = "test"; //name of database

@$conn = mysql_connect("localhost", $DBUserName, $DBPassword) or die('<br />1-Cannot connect to the database at the moment.<br /><br />Please try again later.<br />'); //connect to mysql
@$isDbSelected = mysql_select_db($DBName, $conn) or die('<br />1-Cannot connect to the database at the moment.<br /><br />Please try again later.<br />'); //connect to the db
//----------------------------------------------------------------------------------------------------------------------

include('Paginator.php');

if (!isset($_SESSION['pageMaker'])) {
$linesPerPage = 5; //number of lines to print per page
$numLinksDisplay = 5; //number of page links to display at a time
$query = 'select * from tblperson';
$pageMaker = new Paginator($linesPerPage, $numLinksDisplay, $query, $conn);
} else {
$pageMaker = unserialize($_SESSION['pageMaker']);
}

//set current page
if (isset($_GET['type']))
$pageMaker->setCurrPage($_GET['type'], $_GET['txtPgNum']);

//------------------------------------------------------------
//Code to retrieve the rows to display on the current page
//------------------------------------------------------------
if (!$rs = $pageMaker->getPageRecords($conn))
die('<p>**ERROR - cannot get records for the page at the moment.</p>');
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<title>Pagination</title>
<!-- add the stylesheet for the page links -->
<?php echo $pageMaker->getLinkStyles(); ?>
</head>
<body>
<!-- Display the page links -->
<div id="page_links_wrapper">
<?php echo $pageMaker->showLinks(); ?>
</div>
<!-- Code block to display the DB records for this page-->
<table>
<?php
while ($row = mysql_fetch_assoc($rs)) {
echo '<tr><td>' . $row['fldPersonID'] . '</td><td>' . $row['fldGivenName'] . '</td><td>' . $row['fldFamilyName'] . '</td></tr>';
}
mysql_free_result($rs);
mysql_close($conn);
?>
</table>
<!-- End of code block to display the DB records for this page-->
<?php
//hide or display the 'previous' and 'next' buttons as required
$pageMaker->applyLinkStyles();
//serialise the session's pageMaker object for the next call to this page
$_SESSION['pageMaker'] = serialize($pageMaker);
?>
</body>
</html>


Paginator.php


<?php

class Paginator {

// Properties
protected $linesPerPage; //number of lines to print per page
protected $numLinksDisplay; //number of page links to display at a time
protected $query;
protected $currPage;
protected $totRows;
protected $totPages;
protected $offset;
/* * *********************************************************************
Class Constructor
* ********************************************************************* */
public function __construct($numLines, $numLinks, $query, $conn) {
$this->linesPerPage = ceil($numLines);
$this->numLinksDisplay = ceil($numLinks);
$this->query = $query;
$this->currPage = 1;
$this->offset = 0;

$this->initialise($conn);
}
/* * *********************************************************************
Class Accessor Methods
* ********************************************************************* */
public function setQuery($query, $conn) {
$this->query = $query;
$this->initialise($conn);
}
//-------------------------------------------------------------------------
public function setCurrPage($type, $pageNum) {
$pageNum = ceil($pageNum);
//check which link was clicked
switch ($type) {
case 'pageLink':
$this->currPage = $pageNum;
break;
case 'prevNext':
$this->currPage = $this->currPage + $pageNum;
if ($this->currPage < 1) {
$this->currPage = 1;
}
if ($this->currPage > $this->totPages) {
$this->currPage = $this->totPages;
}
break;
case 'firstPg':
$this->currPage = 1;
break;
case 'lastPg':
$this->currPage = $this->totPages;
break;
}
//calculate the offset of the first record number to retrieve from the DB for this page
$this->offset = ($this->currPage * $this->linesPerPage) - $this->linesPerPage;
if ($this->offset < 0) {
$this->offset = 0;
}
if ($this->offset > $this->totRows) {
$this->offset = $this->totRows;
}
}
//-----------------------------------------------
public function getCurrPage() {
return $this->currPage;
}

/* * *********************************************************************
Class Methods
* ********************************************************************* */
private function initialise($conn) {
//count all the records to work out max number of rows and number of pages needed
$rs = @mysql_query($this->query, $conn) or die("<p>3-Server is busy.<br />Please try again later.</p>");
$this->totRows = mysql_num_rows($rs); //total number of rows to display
@mysql_free_result($rs);
if ($this->totRows % $this->linesPerPage == 0) {
$this->totPages = $this->totRows / $this->linesPerPage;
} else {
$this->totPages = round(($this->totRows / $this->linesPerPage) + 0.5); //total number of pages required
}
$this->numLinksDisplay = ($this->numLinksDisplay > $this->totPages) ? $this->totPages : $this->numLinksDisplay;
//echo $this->totRows.'<br />'.$this->totPages.'<br />'.$this->numLinksDisplay; die();
}
//-------------------------------------------------------------------------------------
public function getPageRecords($conn) {
$query = $this->query . ' limit ' . $this->offset . ',' . $this->linesPerPage;
$rs = @mysql_query($query, $conn);
if (!$rs) {
return false;
} else {
return $rs;
}
}
//-------------------------------------------------------------------------------------
public function showLinks() {
if ($this->totPages <= 1)
return; //no need to display any links
$str = '<div id="page_links_wrap">' .
'<div id="page_links_summ">' .
'<p id="totPages">Total pages: ' . $this->totPages . '</p>' .
'<p id="totRows">Total records: ' . $this->totRows . '</p>' .
'</div>' .
'<div id="page-links-container">' .
'<ul id="page-links">' .
'<li id="liFirstPage"><a href="' . $_SERVER['PHP_SELF'] . '?txtPgNum=-1&amp;type=firstPg" title="Click to view first page">First</a></li>' .
'<li id="liPrevPage"><a href="' . $_SERVER['PHP_SELF'] . '?txtPgNum=-1&amp;type=prevNext" title="Click to view previous page">Previous</a></li>';
//calculate the min and max link numbers to display for this page
if ($this->numLinksDisplay % 2 == 0) { //even number of links to display
$limit1 = $this->currPage - $this->numLinksDisplay / 2;
$limit2 = $this->currPage + ($this->numLinksDisplay / 2) - 1;
} else { //odd number of links to display
$limit1 = $this->currPage - ($this->numLinksDisplay - 1) / 2;
$limit2 = $this->currPage + ($this->numLinksDisplay - 1) / 2;
}
if ($limit1 < 1 && $this->currPage < $this->numLinksDisplay)
$limit1 = 1;
if ($limit2 > $this->totPages)
$limit2 = $this->totPages;
//adjust the link numbers for when we are within $_SESSION['numLinksDisplay']/2 of either end
if ($this->currPage <= $this->numLinksDisplay / 2)
$limit2 = $this->numLinksDisplay;
if ($this->currPage > $this->totPages - $this->numLinksDisplay / 2)
$limit1 = $this->totPages - $this->numLinksDisplay + 1;
//echo '<br />'.$_SESSION['currPage'].'<br />'.$limit1.'<br />'.$limit2.'<br /><br />';
//display the page links
for ($i = $limit1; $i <= $limit2; $i = $i + 1) {
$str = $str . '<li id="liPg' . $i . '"><a href="' . $_SERVER['PHP_SELF'] . '?txtPgNum=' . $i . '&amp;type=pageLink" title="Go to page ' . $i . '">' . $i . '</a></li>';
}

$str = $str . '<li id="liNextPage"><a href="' . $_SERVER['PHP_SELF'] . '?txtPgNum=1&amp;type=prevNext" title="Click to view next page">Next</a></li>' .
'<li id="liLastPage"><a href="' . $_SERVER['PHP_SELF'] . '?txtPgNum=-1&amp;type=lastPg" title="Click to view last page">Last</a></li>' .
'</ul>' .
'</div>' .
'</div>';

return $str;
}
//-------------------------------------------------------------------------------------
public function getLinkStyles() {
if ($this->totPages <= 1) {
return; //no need to display any links
}
$str = '<style type="text/css"> ' .
'#page_links_wrap {' .
//'border: 1px solid green; ' .
'margin: 5px 0px 0px 0px; ' .
'padding: 0px 0px 0px 0px; ' .
'width: 270px}' .
'#page-links-container { ' .
'font-size: 8pt; ' .
'font-family: tahoma, arial, sans serif; ' .
'margin: 0px 0px 0px 0px; ' .
'padding: 0px 0px 0px 0px} ' .
'#page-links-container ul { ' .
'clear: both; ' .
'padding: 0px 0px 0px 0px; ' .
'margin: 0px 0px 10px 0px;' .
'list-style-type: none} ' .
'#page-links-container ul li { ' .
'display: inline; ' .
'color: rgb(0,0,205); ' .
'padding: 3px 4px 3px 4px; ' .
'margin: 0px 0px 0px 6px} ' .
'#page-links-container ul li a { ' .
'text-decoration: none; ' .
'font-size: 8pt} ' .
'#page-links-container ul li a:hover { ' .
'text-decoration: underline} ' .
'#page-links-container ul li a:visited { ' .
'color: rgb(0,0,205);} ' .
'#page_links_summ { ' .
'font-size: 8pt; ' .
'font-family: tahoma, arial, sans serif; ' .
'overflow: hidden} ' .
'#totPages { ' .
//'border: 1px solid blue; ' .
'margin: 5px 0px 5px 10px; padding: 0px 0px 0px 0px;' .
'float: left} ' .
'#totRows { ' .
//'border: 1px solid red; ' .
'margin: 5px 10px 5px 0px; padding: 0px 0px 0px 0px;' .
'float: right} ' .
'</style> ';
return $str;
}
//--------------------------------------------------------------------------------------
public function applyLinkStyles() {
if ($this->totPages <= 1)
return; //no need to display any links
//hide or display the 'previous' and 'next' buttons as required
if ($this->totPages == 1)
echo '<script type="text/javascript">document.getElementById("page-links-container").style.display="none";</script>';
if ($this->currPage == 1) {
echo '<script type="text/javascript">document.getElementById("liPrevPage").disabled = true;</script>';
} else {
echo '<script type="text/javascript">document.getElementById("liPrevPage").disabled = false;</script>';
}
if ($this->currPage == $this->totPages) {
echo '<script type="text/javascript">document.getElementById("liNextPage").disabled = true;</script>';
} else {
echo '<script type="text/javascript">document.getElementById("liNextPage").disabled = false;</script>';
}
//highlight the current page's page link
echo '<script type="text/javascript">document.getElementById("liPg' . $this->currPage . '").style.backgroundColor="rgb(200,200,200)";</script>';
echo '<script type="text/javascript">document.getElementById("liPg' . $this->currPage . '").style.border="1px solid rgb(0,0,0)";</script>';
}
//--------------------------------------------------------------------------------------
}
//end of class
?>
CREATE TABLE `tblperson` (
`fldPersonID` int(11) NOT NULL AUTO_INCREMENT,
`fldFamilyName` varchar(20) DEFAULT NULL,
`fldGivenName` varchar(20) DEFAULT NULL,
PRIMARY KEY (`fldPersonID`)
) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;

/*Data for the table `tblperson` */

insert into `tblperson`(`fldFamilyName`,`fldGivenName`) values ('Sui','Steven');
insert into `tblperson`(`fldFamilyName`,`fldGivenName`) values ('Student','Mary');
insert into `tblperson`(`fldFamilyName`,`fldGivenName`) values ('Student','Sam');
insert into `tblperson`(`fldFamilyName`,`fldGivenName`) values ('Malik','Moore');
insert into `tblperson`(`fldFamilyName`,`fldGivenName`) values ('Soo','Malinda');
insert into `tblperson`(`fldFamilyName`,`fldGivenName`) values ('flinstone','fred');
insert into `tblperson`(`fldFamilyName`,`fldGivenName`) values ('rubble','barney');
insert into `tblperson`(`fldFamilyName`,`fldGivenName`) values ('flinstone','wilma');
insert into `tblperson`(`fldFamilyName`,`fldGivenName`) values ('flinstone','pebbles');
insert into `tblperson`(`fldFamilyName`,`fldGivenName`) values ('smart','maxwell');
insert into `tblperson`(`fldFamilyName`,`fldGivenName`) values ('Soo','Malinda');
insert into `tblperson`(`fldFamilyName`,`fldGivenName`) values ('Sui','Steven');
insert into `tblperson`(`fldFamilyName`,`fldGivenName`) values ('Student','Mary');
insert into `tblperson`(`fldFamilyName`,`fldGivenName`) values ('Student','Sam');
insert into `tblperson`(`fldFamilyName`,`fldGivenName`) values ('Malik','Moore');
insert into `tblperson`(`fldFamilyName`,`fldGivenName`) values ('Soo','Malinda');
insert into `tblperson`(`fldFamilyName`,`fldGivenName`) values ('flinstone','fred');
insert into `tblperson`(`fldFamilyName`,`fldGivenName`) values ('rubble','barney');
insert into `tblperson`(`fldFamilyName`,`fldGivenName`) values ('flinstone','wilma');
insert into `tblperson`(`fldFamilyName`,`fldGivenName`) values ('flinstone','pebbles');
insert into `tblperson`(`fldFamilyName`,`fldGivenName`) values ('smart','maxwell');
insert into `tblperson`(`fldFamilyName`,`fldGivenName`) values ('Soo','Malinda');
insert into `tblperson`(`fldFamilyName`,`fldGivenName`) values ('Sui','Steven');
insert into `tblperson`(`fldFamilyName`,`fldGivenName`) values ('Student','Mary');
insert into `tblperson`(`fldFamilyName`,`fldGivenName`) values ('Student','Sam');
insert into `tblperson`(`fldFamilyName`,`fldGivenName`) values ('Malik','Moore');
insert into `tblperson`(`fldFamilyName`,`fldGivenName`) values ('Soo','Malinda');
insert into `tblperson`(`fldFamilyName`,`fldGivenName`) values ('flinstone','fred');
insert into `tblperson`(`fldFamilyName`,`fldGivenName`) values ('rubble','barney');
insert into `tblperson`(`fldFamilyName`,`fldGivenName`) values ('flinstone','wilma');
insert into `tblperson`(`fldFamilyName`,`fldGivenName`) values ('flinstone','pebbles');
insert into `tblperson`(`fldFamilyName`,`fldGivenName`) values ('smart','maxwell');
insert into `tblperson`(`fldFamilyName`,`fldGivenName`) values ('Soo','Malinda');
insert into `tblperson`(`fldFamilyName`,`fldGivenName`) values ('Sui','Steven');
insert into `tblperson`(`fldFamilyName`,`fldGivenName`) values ('Student','Mary');
insert into `tblperson`(`fldFamilyName`,`fldGivenName`) values ('Student','Sam');
insert into `tblperson`(`fldFamilyName`,`fldGivenName`) values ('Malik','Moore');
insert into `tblperson`(`fldFamilyName`,`fldGivenName`) values ('Soo','Malinda');
insert into `tblperson`(`fldFamilyName`,`fldGivenName`) values ('flinstone','fred');
insert into `tblperson`(`fldFamilyName`,`fldGivenName`) values ('rubble','barney');
insert into `tblperson`(`fldFamilyName`,`fldGivenName`) values ('flinstone','wilma');
insert into `tblperson`(`fldFamilyName`,`fldGivenName`) values ('flinstone','pebbles');
insert into `tblperson`(`fldFamilyName`,`fldGivenName`) values ('smart','maxwell');
insert into `tblperson`(`fldFamilyName`,`fldGivenName`) values ('Soo','Malinda');

susanv
04-27-2011, 12:45 PM
Thank you very much, I'm going to try it. Much appreciated!

bullant
04-27-2011, 12:48 PM
no problem :)



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum