PDA

View Full Version : pagination class



firepages
12-12-2005, 04:00 AM
Note , I have removed most of the comments for brevity & since its mostly straightforward anyway.
Error checks have been removed for brevity !

da class ...


<?php
/**
* firepages.com.au - basic pagination class - see
* http://www.firepages.com.au/pagination.htm for more information
*/
class pager{
var $p_range = 0; # range to show if you dont want to show ALL pages returned
var $curr = 1; # current page number
var $_pages = ''; # no of pages in a recordset
var $_ctl = '_p'; # default control variable name
var $_req_url =''; # url to build links with
var $_req_qs =''; # query string to build links with
# allowed replacements for titles and links
var $_t_tpls = array('{CURRENT}','{FROM}','{TO}','{MAX}','{TOTAL}');
var $_l_tpls = array('{LINK_HREF}','{LINK_LINK}');
#when set_range() is in use
var $set_from=''; #min page number of returned set
var $set_to=''; #max number of returned set

function pager($max, $pp, $curr, $extra='')
{
if(!is_array($extra)){
$extra=array();
}
$this->_pp = $pp;
$this->curr = (int)$curr > 0 ? $curr : 1 ;
$this->set_from=1;//may be overriden by a set_range() paged set
$this->_pages = $this->set_to = $this->p_range = ceil( $max/$pp );
$this->_ctl .= empty($extra['suffix']) ? '' : $extra['suffix'] ;
$this->_req_qs = isset($extra['query_string']) ?
$extra['query_string'] : $_SERVER['QUERY_STRING'] ;
$this->_req_url = isset($extra['php_self']) ?
$extra['php_self'] : $_SERVER['PHP_SELF'] ;

#check for and remove control variables from query string#
if(strpos($this->_req_qs,$this->_ctl)!==false){
parse_str($this->_req_qs,$arr);
$tmp=array();
unset($arr[$this->_ctl]);
foreach($arr as $k=>$v){
$tmp[]="$k=$v";
}
$this->_req_qs = implode('&', $tmp);
unset($tmp);
}
#vars for eye_candy not declared ~#
$this->_from = (($this->curr * $this->_pp) - $this->_pp) + 1;
$to = ($this->_from + $this->_pp) -1 ;
$this->_to = ($to > $max ) ? $max : $to ;
$this->_total = $max ;
}

function set_range($p_range)
{
$this->p_range = $p_range;
}

function get_limit()
{
return ($this->curr * $this->_pp) - $this->_pp. ' , '.$this->_pp;
}

function get_limit_offset()
{
return ($this->curr * $this->_pp) - $this->_pp;
}

function get_title($format)
{
return str_replace($this->_t_tpls,
array($this->curr, $this->_from, $this->_to, $this->_pages, $this->_total), $format);
}

function _get_qurl()
{
$q = empty($this->_req_qs) ? '' : '?'.$this->_req_qs ;
$s = (substr($q, 0, 1) == '?') ? '&amp;' : '?' ;
return $this->_req_url . $q . $s . $this->_ctl . '=';
}

function get_prev($format)
{
return $this->curr > 1 ?
str_replace($this->_l_tpls,array($this->_get_qurl().($this->curr -1)),$format) : '' ;
}

function get_next($format)
{
return ($this->curr < $this->_pages) ?
str_replace($this->_l_tpls,array($this->_get_qurl().($this->curr +1)),$format) : '' ;
}

function get_range($format, $sep,$first='',$last='')
{
if($this->_pages < 2){
return ;
}
$pre_url = $this->_get_qurl();
$lfirst = $llast = '' ;
$min = 1 ;
$to = $this->_pages ;

if($this->_pages > $this->p_range){
$mid = ceil(($this->p_range / 2));
if(($this->curr - $mid) >= 1){
$min = $this->curr - $mid;
}
$to = $min + ($this->p_range-1);
if($this->_pages > $to){
$llast = (!empty($last)) ?
$sep.str_replace($this->_l_tpls,array($pre_url.$this->_pages,$last),$format) : '' ;
}
if($min > 1){
$lfirst = (!empty($first) && $this->curr >1 ) ?
str_replace($this->_l_tpls,array($pre_url.'1',$first),$format) .$sep : '' ;
}
if($to > $this->_pages){
$to = $this->_pages ;
}
//NEW readjust to show at least p_range links is set_range in use//
if(($to - $min) < $this->p_range){
$min= ($to-$this->p_range)+1;
}
//NEW external parsers may need the correct from and to values from a set_range() limited set
$this->set_from=$min;
$this->set_to=$to;
}
for($x=$min; $x<=$to; ++$x){
$rets[]=($this->curr!=$x)?str_replace($this->_l_tpls, array($pre_url.$x, $x) , $format):$x;
}
return $lfirst.implode($sep, $rets).$llast;
}
}
?>


This class provides only the basics of pagination , it makes no queries itself, all it does is provide you with information about the results and links to go forward and backwards through your result set.

Its actually a good idea to keep SQL and specific database information out of your pagination class since it makes your code more reusable.
If you have a common database abstraction class you could agregate that into such a class but I think it would still be better to subclass such a solution and keep the pagination class as pure as possible.

Also to keep markup out of the class this class requires you pass your own formatting for page results and links, again it does make it more flexible in the long run.

Note that to make pagination efficient you normally end up making 2 queries , 1 to fetch the count , the next to fetch the actual data for display, with a properly indexed table this is not a big ask of the DB.

example basic usage...

Ideally you would use a function or create a subclass of the pager class to make the usage `neater` , its quite easy to wrap the above up for quicker coding.
The following example is at its most basic.


<?php
//find out the size of our recordset , only fetch a count, in this query nothing else
$max = mysql_result( mysql_query("SELECT COUNT(id) FROM table WHERE id > 0"), 0 ) ;
$pager = new pager(
$max , /*see above*/
10 , /*how many records to display at one time*/
@$_GET['_p'] /*this is the current page no carried via _GET*/
) ;

/*
optionally set a maximum number of pages to display
so you dont end up with 100's of links
*/
$pager->set_range(10);

/*the main query note the same WHERE conditions*/
$q = mysql_query("SELECT id,name FROM table WHERE id > 0 LIMIT ".$pager->get_limit());

/*show something for your troubles*/
echo $pager->get_title('Page {CURRENT} of {MAX}<br />Displaying results {FROM} to {TO} of {TOTAL}'). ' <br />';
echo $pager->get_range('<a href="{LINK_HREF}">{LINK_LINK}</a>',' &raquo ').'<br /><br />';

/*+ of course the actual data*/
while($r = mysql_fetch_assoc($q)){
echo "{$r['id']},{$r['name']}<br />";
}
?>


any feedback , suggestions, glaring errors etc appreciated.

22/01/2005
changed '&' to &amp; (Rich Pedley)
Added optional 'first' and 'last' links to get_range , first and last links only get shown if requested and is a first and last link is actually relevant....


echo $pager->get_range('<a href="{LINK_HREF}">{LINK_LINK}</a>',' &raquo ','First','Last').'<br /><br />';
//these could also be images/anything '<img src="first.jpg" />' etc


10/02/2005
Added get_prev() and get_next() for page by page navigation,
this did mean a change elsewhere in the class (gave get_qurl its own function) so if you are using a modified version check first.


echo $pager->get_prev('<a href="{LINK_HREF}">Prev</a>');
echo $pager->get_next('<a href="{LINK_HREF}">text or image here</a>');


17/02/1006
Fixed borked display when using get_range();
Added get_offset_limit() which returns the current offset for databases that can't handle the comma returned in get_limit()

5/5/2007
Added $pager->set_from & $pager->set_to variables for external routines that need to know the first and last page numbers of a set when using set_range();

5/5/2007
now displays a minimum of (e.g. with $pager->set_range(10)) 10 pages even when at end of set (previously might only display set_range()/2 links)

28/6/1007
StupidRalph just pointed out that there is the possibility of XSS in the code above & he is quite right.
I will not however be adding any checks for tainted data in the class above for the following reason.

There are so many places in a reasonably sized application for tainted data to cause havoc which means that there can be hundreds of bits of code that require tainted data to be escaped or otherwise processed, because of that I now filter all incoming data long before that data gets anywhere near my classes or functions... e.g. any page should..
initialize (load config vars etc)
iterate through all potential sources of trouble and clean (GET, POST COOKIE etc)
then and only then load the logic of your the application and play with data.

Much code is distributed with built in error/injection checks, this is ok until you realize you may end up doing the same thing to the same data time and time again, also you may not like the authors validation routines and you probably do not want several authors different routines clogging up your code.

So the moral is, the class above is insecure unless you already employ some pre-filtering of GPC data.

Velox Letum
12-12-2005, 06:36 AM
Very nice. This could save massive amounts of time in writing pagination code, for my own site. I like how flexible it is in the display of the page links and such, especially how you can easily integrate it into current queries by just modifying the code a bit and making a call to your class. Great job! =)

shinko_metsuo
01-21-2006, 08:10 PM
This is really helpful. I'd reccomend it to anyone :thumbsup:

Rich Pedley
01-21-2006, 09:28 PM
Hmm I have a problem with this class, which i am looking into but haven't solved yet.(and i want to use it cause it looks funky :-) )
On using:

$pager->set_range(10);

I get the following on first entering the page:

Page 1 of 2
Displaying results 1 to 3 of 6
1 &#187; 2 &#187; 3 &#187; 4 &#187; 5 &#187; 6 &#187; 7 &#187; 8 &#187; 9 &#187; 10

page 1 looks like this:
Page 1 of 2
Displaying results 1 to 3 of 6
1 &#187; 2 &#187; 3 &#187; 4 &#187; 5 &#187; 6 &#187; 7 &#187; 8 &#187; 9 &#187; 10


page 2 looks like this:
Page 2 of 2
Displaying results 4 to 6 of 6
0 &#187; 1 &#187; 2

extra pages all look like this:
Page 3 of 2
Displaying results 7 to 6 of 6
0 &#187; 1 &#187; 2


Plus any chance of adding an option for the following:
forward/back previous/next or whatever people want to use
First page/Last page

Rich Pedley
01-21-2006, 10:04 PM
and a nother quick suggested alteration(line 77):

$s = (substr($q, 0, 1) == '?') ? '&amp;' : '?' ;
changing the & to &amp; will satisfy validators, and is safer to use.

firepages
01-22-2006, 04:27 AM
Page 1 of 2
Displaying results 1 to 3 of 6


with a range of 10 that should only return 1 page... I can't reproduce this , so I am guessing that the WHERE clause in your counting query is not the same as the WHERE in your actual query ?? , if not could you post your code ?

Made the &amp; change cheers !
Added optional 'first' and 'last' replacer arguments to get_range() , you dont have to pass them & if you do they currently only get shown if relevant, need to do some more checking but I can smell lunch :D

Velox Letum
01-22-2006, 10:56 AM
It does this for me too, and it can also go into negative numbers.

-3 -2 -1 0 1 2 3 (for example).

firepages
01-22-2006, 03:58 PM
doh , sorry for casting asparagus ~ twas indeed me.
class should now work as expected (& yes I spotted the problem if per_page is odd, will fix)

Rich Pedley
01-22-2006, 05:07 PM
'First' appear to show on page 1 for me, surely it shouldn't show until page 2 and greater?

firepages
01-22-2006, 05:54 PM
cool ,done.
change this
$lfirst = (!empty($first)) ? str_replace($this->_l_tpls,array($pre_url.'1',$first),$format) .$sep : '' ;
to this
$lfirst = (!empty($first) && $this->curr >1 ) ? str_replace($this->_l_tpls,array($pre_url.'1',$first),$format) .$sep : '' ;

Rich Pedley
01-22-2006, 08:55 PM
Excellent, and many thanks this is the first pagination class I have seen that actually worked how I wanted it to!

In your example you gave basic instructions for displayin the output, for anyone that is interested I have added in the following:


//after the $max= query
if(isset($_GET['view']))$records=$max;

//and then for displaying the pagination:
echo '<div class="paginate">';
if($pager->_pages >= 2){
echo $pager->get_title('Viewing page {CURRENT} of {MAX}<br />Displaying results {FROM} to {TO} of {TOTAL}'). ' <br />';
}else{
echo $pager->get_title('Viewing page {CURRENT} of {MAX}'). ' <br />';
}
echo $pager->get_range('<a href="{LINK_HREF}">{LINK_LINK}</a>',' &raquo ','First','Last').'<br />';
//echo $pager->get_range('<a href="{LINK_HREF}">{LINK_LINK}</a>',' &raquo ').'<br /><br />';
if($pager->_pages >= 2){
echo '<a href="'.$_SERVER['PHP_SELF'].'?view=all">View all</a>';
}
echo '</div>';
Adding in a view all link seemed appropiate to me, though I dare say it could be added to the class?

davehaz
01-27-2006, 02:10 PM
help, I am trying to get this to work but I am obviously not doing something correct, are there variable in this script that should be changed?

could someone please explain what needs to be done to make it work?

thanks.

Rich Pedley
01-27-2006, 03:36 PM
we'd need to see your code!

davehaz
01-27-2006, 03:51 PM
sorry, here you go.


<HTML>
<HEAD>
<META NAME="description" CONTENT="Find Mens <?php echo $ssrch2;?> <?php echo $ssrch3;?> at NSBSportswear. Peruse an inventory of over 10 million clothing items at low prices. <?php echo $ssrch;?> <?php echo $ssrch2;?> <?php echo $ssrch3;?> now on sale">
<SCRIPT LANGUAGE="JavaScript">
var maxAdNo = 3
var adNo
var myAd = new Array()
myAd[0] = '<a href="http://www.shareasale.com/r.cfm?b=36651&u=106368&m=7712&urllink=&afftrack=" target="_new"><img src="http://www.nsbsportswear.com/coolibar1.jpg" border="0"></a>'
myAd[1] = '<a href="http://www.shareasale.com/r.cfm?b=44437&u=106368&m=7866&urllink=&afftrack=" target="_new"><img src="http://www.nsbsportswear.com/ea1.gif" border="0"></a>'
myAd[2] = '<a href="http://www.shareasale.com/r.cfm?b=38521&u=106368&m=8112&urllink=&afftrack=" target="_new"><img src="http://www.nsbsportswear.com/wf1.gif" border="0"></a>'
myAd[3] = '<a href="http://www.shareasale.com/r.cfm?b=43478&u=106368&m=8112&urllink=&afftrack=" target="_new"><img src="http://www.nsbsportswear.com/av1.gif" border="0"></a>'
</script>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=iso-8859-1">
</HEAD>
<BODY BGCOLOR="#005D90" LINK="#0000FF" VLINK="#6666FF" ALINK="#0000FF">
<TABLE WIDTH="95%" BORDER="0" CELLSPACING="0" CELLPADDING="0" ALIGN="CENTER">
<TR>
<TD ROWSPAN="3" BGCOLOR="#005D90" WIDTH="1">&nbsp;</TD>
<TD ALIGN="LEFT" VALIGN="TOP" WIDTH="50" BGCOLOR="#FFFFFF"><IMG SRC="http://www.nsbsportswear.com/corner2.png" WIDTH="50" HEIGHT="50"></TD>
<TD ROWSPAN="3" ALIGN="CENTER" VALIGN="MIDDLE">
<TABLE WIDTH="100%" BORDER="0" CELLSPACING="0" CELLPADDING="0" ALIGN="CENTER">
<TR ALIGN="CENTER" VALIGN="MIDDLE" BGCOLOR="#FFFFFF">
<TD COLSPAN="4">
<TABLE WIDTH="650" BORDER="0" CELLSPACING="0" CELLPADDING="0">
<TR>
<TD ALIGN="RIGHT" VALIGN="TOP"><IMG SRC="http://www.nsbsportswear.com/d3.png" WIDTH="25" HEIGHT="25"></TD>
<TD ROWSPAN="3" ALIGN="CENTER" VALIGN="BOTTOM"><A HREF="http://www.nsbsportswear.com" title="NSB Sportswear Home Page"><IMG SRC="http://www.nsbsportswear.com/smithtop.png" WIDTH="600" HEIGHT="80" BORDER="0"></A></TD>
<TD ALIGN="LEFT" VALIGN="TOP"><IMG SRC="http://www.nsbsportswear.com/d4.png" WIDTH="25" HEIGHT="25"></TD>
</TR>
<TR>
<TD>&nbsp;</TD>
<TD>&nbsp;</TD>
</TR>
<TR>
<TD ALIGN="RIGHT" VALIGN="BOTTOM"><IMG SRC="http://www.nsbsportswear.com/d2.png" WIDTH="25" HEIGHT="25"></TD>
<TD ALIGN="LEFT" VALIGN="BOTTOM"><IMG SRC="http://www.nsbsportswear.com/d1.png" WIDTH="25" HEIGHT="25"></TD>
</TR>
</TABLE>
</TD>
</TR>
<TR BGCOLOR="#005D90" VALIGN="MIDDLE">
<TD ALIGN="LEFT" COLSPAN="4">
<TABLE WIDTH="100%" BORDER="0" CELLSPACING="0" CELLPADDING="5" ALIGN="CENTER">
<TR BGCOLOR="#005D90">
<TD>
<TABLE WIDTH="98%" BORDER="2" CELLSPACING="0" CELLPADDING="5" ALIGN="CENTER">
<TR BGCOLOR="#FFFFFF">
<TD ALIGN="LEFT" VALIGN="TOP" WIDTH="100"><B><FONT FACE="Arial, Helvetica, sans-serif" SIZE="2">All
Men's Categories:</FONT></B><br>

<?php
@include('/home/nsbsports/public_html/scripts/pager.php');
if (main) // perform search only if a string was entered.
{
mysql_connect("localhost", "root", "pwd") or die ("Problem connecting to DataBase");
$srch="%".Man."%";
$query = "select * from categorylinks WHERE gender LIKE '$srch'";
$result = mysql_db_query("nsbsportswear_nav", $query);
$num_rows = mysql_num_rows($result);
if ($result)
{
echo "<table width=100% align=left cellspacing=0 cellpadding=1 border=0><tr>
<td align=left WIDTH='100%' Height='0'></td>
</tr>";
while ($r = mysql_fetch_array($result)) { // Begin while
$linktext = $r["display"];
$linkcode = $r["url"];
$linkdesc = $r["title"];
$linkgen = $r["gender"];
$linkcat = $r["category"];
$linkcategory = $r["linkcategory"];
echo "<tr><td align=left><a href='$linkcode' title='$linkdesc'><font size=-1 face-tahoma>$linkcat</font></a></td></tr>";
} // end while
echo "</table>\n";
} else { echo "problems...."; }
} else {
echo "Search string is empty. <br> Go back and type a string to search";
}
?>

</TD>
<TD ALIGN="LEFT" VALIGN="TOP"><?
/* Set current, prev and next page */
$page = (!isset($_GET['page']))? 1 : $_GET['page'];
$prev = ($page - 1);
$next = ($page + 1);
$ppages = ($page - 4); // setup for previous 4 pages
if($page < '4') { $ppages = "";}
$npages = ($page + 9); // setup for next 5 pages
$ssrch="12345";
$ssrch2 ="shirt";
$ssrch3 ="";
$_SESSION['srch'] = $ssrch;
$_SESSION['srch2'] = $ssrch2;
$_SESSION['srch3'] = $ssrch3;
$_SESSION['lookup']=$lookup;
$_SESSION['disnum']=$disnum;
$srch = $_SESSION['srch'];
$srch2 = $_SESSION['srch2'];
$srch3 = $_SESSION['srch3'];
// Set current, prev and next page
$prev = ($page - 1);
$next = ($page + 1);
$_SESSION['prev']=$prev;
$_SESSION['next']=$next;
/* Max results per page */
$max_results = '20'; /* Calculate the offset */

$from = (($page * $max_results) - $max_results);
//$from=$_SESSION['from'];
$dbh=MySQL_connect ("localhost", "root", "pwd")
or die ('I cannot connect to the database because: ' . mysql_error());
mysql_select_db ("apparrell");
$query = "select * from stuff WHERE searchdata LIKE ('% $srch %') AND searchdata LIKE ('% $srch2 %')AND searchdata LIKE ('% $srch3 %')";
$result = mysql_query($query);
$total_results = mysql_num_rows($result);
$total_pages = ceil($total_results / $max_results);

echo "<p align=center><div align=center><H1>Mens $ssrch2 $ssrch3</H1>";

#
#
#
#
#
#
// start of new pagination script
$max = $total_pages;
$pager = new pager(
$max , /*see above*/
20, /*how many records to display at one time*/
@$_GET['_p'] /*this is the current page no carried via _GET*/
) ;
$pager->set_range();
// end of new pagination script



#
#
//and then for displaying the pagination:
#
#
echo '<div class="paginate">';
if($pager->_pages >= 2){
echo $pager->get_title('Viewing page {CURRENT} of {MAX}<br />Displaying results {FROM} to {TO} of {TOTAL}'). ' <br />';
}else{
echo $pager->get_title('Viewing page {CURRENT} of {MAX}'). ' <br />';
}
echo $pager->get_range('<a href="{LINK_HREF}">{LINK_LINK}</a>',' &raquo ','First','Last').'<br />';
echo $pager->get_range('<a href="{LINK_HREF}">{LINK_LINK}</a>',' &raquo ').'<br />';
if($pager->_pages >= 2){
}
echo '</div>';
// end of new pagination script echo
#
#
#
#
#
#
# start of 2nd query and display the results
#
#
#
if($page==1){$from='0';}
$query="select * from stuff WHERE searchdata LIKE ('% $srch %') AND searchdata LIKE ('% $srch2 %') AND searchdata LIKE ('% $srch3 %') ORDER BY NAME ASC LIMIT $from, $max_results";
$result = mysql_query($query);
$rows=mysql_num_rows($result);
echo "</div>";
//Generates the list of chapters
echo "<br><table width=100% align=center cellspacing=0 cellpadding=8 bordercolor=#005D90 border=0><tr>";
while($data1 = mysql_fetch_array($result)) {
extract($data1,EXTR_OVERWRITE);
echo "<td align=center bgcolor=#005D90 WIDTH='50%' Height='5'></td>
<td align=center bgcolor=#005D90 WIDTH='50%' Height='5'></td>
</tr>";
// Begin while
$Item = $data1["NAME"];
$Site_Link = $data1["BUYURL"];
$Buy_Site = $data1["PROGRAMNAME"];
$Buy_Link = $data1["BUYURL"];
$Price = $data1["PRICE"];
$Cat_two = $data1["ADVERTISERCATEGORY"];
$Imp_Link = $data1["IMPRESSIONURL"];
$Image_Link = $data1["IMAGEURL"];
$Desc = $data1["DESCRIPTION"];
$botbrand = $data1["MANUFACTURER"];
$boturl = $data1["BUYURL"];
$uid = $data1["uid"];
$Button_Link = $data1["BUYURL"];
// add these to your scripts to indicate sales price, savings, and % saved
$sale_price = $data1["SALEPRICE"];
$psave = $data1["PSAVE"];
$dsave = $data1["DSAVE"];
echo "<tr>
<td align=left><font face=tahoma size=3><b>$Item</b></font><br><font face =arial size=2>$Desc<br><br>Outlet Priced: $ $Price";
if($dsave > '0.00'){echo "<br><TABLE WIDTH='100%' BORDER='1' CELLSPACING='0' CELLPADDING='5' ALIGN='CENTER' BORDERCOLOR='#005D90' BORDERCOLORLIGHT='#005D90' BORDERCOLORDARK='#005D90'>
<TR ALIGN='CENTER' VALIGN='MIDDLE'>
<TD ALIGN='LEFT' BGCOLOR='#005D90'><FONT FACE='Arial, Helvetica, sans-serif' SIZE='2' COLOR='#FF0000'><B><FONT COLOR='#FFFFFF'>On
Sale!</FONT></B></FONT></TD>
<TD BGCOLOR='#005D90' ALIGN='LEFT'><FONT FACE='Arial, Helvetica, sans-serif' SIZE='2' COLOR='#FFFFFF'><B>$$SALEPRICE</B></FONT></TD>
</TR>
<TR ALIGN='CENTER' VALIGN='MIDDLE'>
<TD ALIGN='LEFT'><FONT FACE='Arial, Helvetica, sans-serif' SIZE='2'><B><FONT COLOR='#005D90'>You
Save!</FONT></B></FONT></TD>
<TD ALIGN='LEFT'><FONT FACE='Arial, Helvetica, sans-serif' SIZE='2' COLOR='#005D90'><B>$$dsave</B></FONT></TD>
</TR>
<TR ALIGN='CENTER' VALIGN='MIDDLE'>
<TD><img src='http://nsbsportswear.com/smile.jpg' BORDER='0'></TD>
<TD BGCOLOR='#005D90' ALIGN='LEFT'><FONT FACE='Arial, Helvetica, sans-serif' SIZE='2'><B><FONT COLOR='#FFFFFF'>That's<BR>
$psave%</FONT></B></FONT></TD>
</TR>
</TABLE>";}
echo"<br>Offered by: <a href='$Site_Link&afsrc=1' target='_new'>$Buy_Site
</a></td>";
echo "<td align=center><img src='$Image_Link' alt='$Item, offered by $Buy_Site, $ $Price'><br>";echo"<br><a href='$Site_Link&afsrc=1' target='_new'><img src='http://www.nsbsportswear.com/images/ss.jpg' border='0'></a></td></tr>"; } // end while
echo "</table>\n";
echo "<div align=center>";
echo "</div>";
?><br><div align="center"><SCRIPT TYPE="text/javascript"><!--
google_ad_client = "pub-3062514307296645";
google_ad_width = 336;
google_ad_height = 280;
google_ad_format = "336x280_as";
google_ad_type = "text";
google_ad_channel ="5909127837";
google_color_border = "005D90";
google_color_bg = "FFFFFF";
google_color_link = "0000FF";
google_color_url = "0000FF";
google_color_text = "000000";
//--></SCRIPT>
<SCRIPT TYPE="text/javascript"
SRC="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</SCRIPT></div></TD>
<TITLE>NSB Sportswear Outlet - Mens <?php echo $ssrch2;?> <?php echo $ssrch3;?></TITLE>
<TD ALIGN="LEFT" VALIGN="TOP" WIDTH="120">
<TABLE WIDTH="100%" BORDER="2" CELLSPACING="0" CELLPADDING="3" BGCOLOR="#005D90" BORDERCOLOR="#005D90" ALIGN="CENTER">
<TR ALIGN="CENTER" VALIGN="MIDDLE" BGCOLOR="#FFFFFF">
<TD><A HREF="http://www.nsbsportswear.com/men/index.html"><IMG SRC="http://www.nsbsportswear.com/images/men.jpg" WIDTH="100" HEIGHT="18" BORDER="0" ALT="Men's Sportswear"></A></TD>
</TR>
<TR ALIGN="CENTER" VALIGN="MIDDLE" BGCOLOR="#FFFFFF">
<TD><A HREF="http://www.nsbsportswear.com/women/index.html"><IMG SRC="http://www.nsbsportswear.com/images/women.jpg" WIDTH="100" HEIGHT="18" BORDER="0" ALT="Women's Sportswear"></A></TD>
</TR>
<TR ALIGN="CENTER" VALIGN="MIDDLE" BGCOLOR="#FFFFFF">
<TD><A HREF="http://www.nsbsportswear.com/kids/index.html"><IMG SRC="http://www.nsbsportswear.com/images/kids.jpg" WIDTH="100" HEIGHT="18" BORDER="0" ALT="Kids Sportswear"></A></TD>
</TR>
<TR ALIGN="CENTER" VALIGN="MIDDLE" BGCOLOR="#FFFFFF">
<TD><A HREF="http://www.nsbsportswear.com/coupons.htm" TARGET="_blank"><IMG SRC="http://www.nsbsportswear.com/images/coupons.jpg" WIDTH="100" HEIGHT="18" BORDER="0" ALT="Get Coupons"></A></TD>
</TR>
<TR ALIGN="CENTER" VALIGN="MIDDLE" BGCOLOR="#FFFFFF">
<TD><A HREF="http://www.nsbsportswear.com/search.htm" TARGET="_blank"><IMG SRC="http://www.nsbsportswear.com/images/searchb.jpg" WIDTH="100" HEIGHT="18" BORDER="0"></A></TD>
</TR>
<TR ALIGN="CENTER" VALIGN="MIDDLE" BGCOLOR="#FFFFFF">
<TD><A HREF="http://www.nsbsportswear.com/brand/index.html"><IMG SRC="http://www.nsbsportswear.com/images/brand.jpg" WIDTH="100" HEIGHT="50" BORDER="0"></A></TD>
</TR>
</TABLE>
<BR><SCRIPT LANGUAGE="JavaScript">
adNo = Math.round(Math.random() * maxAdNo)
document.write(myAd[adNo])
</SCRIPT><br><br>
</TD>
</TR>
</TABLE>
</TD>
</TR>
</TABLE>
</TD>
</TR>
<TR ALIGN="CENTER" VALIGN="MIDDLE" BGCOLOR="#FFFFFF">
<TD COLSPAN="4">
<TABLE WIDTH="650" BORDER="0" CELLSPACING="0" CELLPADDING="0">
<TR>
<TD ALIGN="RIGHT" VALIGN="TOP"><IMG SRC="http://www.nsbsportswear.com/d3.png" WIDTH="25" HEIGHT="25"></TD>
<TD ROWSPAN="3" ALIGN="CENTER" VALIGN="BOTTOM"><A HREF="http://www.nsbsportswear.com" title="NSB Sportswear Home Page"><IMG SRC="http://www.nsbsportswear.com/smithtop.png" WIDTH="600" HEIGHT="80" BORDER="0"></A></TD>
<TD ALIGN="LEFT" VALIGN="TOP"><IMG SRC="http://www.nsbsportswear.com/d4.png" WIDTH="25" HEIGHT="25"></TD>
</TR>
<TR>
<TD>&nbsp;</TD>
<TD>&nbsp;</TD>
</TR>
<TR>
<TD ALIGN="RIGHT" VALIGN="BOTTOM"><IMG SRC="http://www.nsbsportswear.com/d2.png" WIDTH="25" HEIGHT="25"></TD>
<TD ALIGN="LEFT" VALIGN="BOTTOM"><IMG SRC="http://www.nsbsportswear.com/d1.png" WIDTH="25" HEIGHT="25"></TD>
</TR>
</TABLE>
</TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="RIGHT" VALIGN="TOP" WIDTH="50" BGCOLOR="#FFFFFF"><IMG SRC="http://www.nsbsportswear.com/corner.png" WIDTH="50" HEIGHT="50"></TD>
</TR>
<TR>
<TD BGCOLOR="#FFFFFF">&nbsp;</TD>
<TD BGCOLOR="#FFFFFF">&nbsp;</TD>
</TR>
<TR>
<TD ALIGN="LEFT" VALIGN="BOTTOM" BGCOLOR="#FFFFFF"><IMG SRC="http://www.nsbsportswear.com/corner3.png" WIDTH="50" HEIGHT="50"></TD>

<TD ALIGN="RIGHT" VALIGN="BOTTOM" BGCOLOR="#FFFFFF"><IMG SRC="http://www.nsbsportswear.com/corner4.png" WIDTH="50" HEIGHT="50"></TD>
</TR>
</TABLE>
</BODY>
</HTML>



and I just copied the code from above.

thanks.

Rich Pedley
01-27-2006, 08:14 PM
I'll be honest, your code is a little bit difficult to go through.

You appear to have another form of pagination in there as well, that certainly won't help.

I also cannot find the equivalent to this:
$max = mysql_result( mysql_query("SELECT COUNT(id) FROM table WHERE id > 0"), 0 ) ;
But I may have missed it.

similarily:
$q = mysql_query("SELECT id,name FROM table WHERE id > 0 LIMIT ".$pager->get_limit());
As such this leads me to believe that other portions may be missing as well.

Rather than code it for you, can i suggest you copy your code, strip out all the unnecessary bits, and rebuild from there. (even remove all the tables, have a bare bones mysql connection/pull results/pagination/display results). From there you would be able to work backwards to integrate it into your existing page. By doing it this way you'll learn how the thing works as you go along.

Hope that helps.

Others may of course be able to help straight away :-)

davehaz
01-28-2006, 09:23 PM
got it, thanks for the advice, very cool script, do you by chance have a commented version of pager.php, I am relatively new to php and there are things happening in that script that I don't understand.

thanks.

Rich Pedley
01-28-2006, 10:17 PM
I don't, but then i didn't write it. Plus comments in my scripts tend to be very bague even when i dod remember to add them !!

davehaz
01-29-2006, 02:57 PM
I am looking at pager.php and don't understand a few things going on, I have never seen this done before in php.


class pager{
var $p_range = 0; # range to show if you dont want to show ALL pages returned
var $curr = 1; # current page number
var $_pages = ''; # no of pages in a recordset
var $_ctl = '_p'; # default control variable name
var $_req_url =''; # url to build links with
var $_req_qs =''; # query string to build links with



I realize this is just setting up variable for the class but have never seen variable declared like this in php, is this normal to do when creating a class?

also
I don't understand what is happening here, I have never seen this used before.


function pager($max, $pp, $curr, $extra='')
{
$this->_pp = $pp;
$this->curr = (int)$curr > 0 ? $curr : 1 ;
$this->_pages = $this->p_range = ceil( $max/$pp );
$this->_ctl .= empty($extra['suffix']) ? '' : $extra['suffix'] ;
$this->_req_qs = isset($extra['query_string']) ? $extra['query_string'] : $_SERVER['QUERY_STRING'] ;
$this->_req_url = isset($extra['php_self']) ? $extra['php_self'] : $_SERVER['PHP_SELF'] ;


does this mean that variable $this is being copied to variable _pp and so on?
what does -> do in php?

hate to be a pain, but I hate even more to use code that I don't understand.

thanks.

firepages
01-29-2006, 03:13 PM
yes
$this->_pp = $pp;

Now the class variable $this->_pp holds the value of $pp and can be used anywhere within the pager class without having to globalise it or pass it around.
The '_' is supposed to signify a private variable but in PHP4 it still can be accessed externally or from subclasses etc.

As for the assignment of variables when declared, once upon a time I was told it was bad juju , but its standard in PHP5 to do so and it works in PHP4 just as well.

Take a look in the manual for a quick primer in PHP OOP

davehaz
02-02-2006, 12:41 AM
howdy,
hey what does the last ,0 do in this query?


$max = mysql_result( mysql_query("SELECT COUNT(id) FROM table WHERE id > 0"), 0 ) ;

is it necessary? I tried to run it in mysql and it kept coming up with an error until I got rid of it.

thanks.

firepages
02-02-2006, 01:24 AM
its the same as doing this

$res = mysql_query("SELECT COUNT(id) FROM table WHERE id > 0");
$max = mysql_result($res,0);

but as a one liner , see mysql_result() (http://www.php.net/mysql_result) in the manual for more info

fci
02-02-2006, 05:55 PM
I usually use the following to obtain a count:

SELECT COUNT(1) FROM table WHERE clause

guvenck
02-03-2006, 03:07 AM
firepages, you wrote a great class, congratulations, I didn't have any difficulties using it. Also thanks for leaving the localization to the php page, not to the class itself. I didn't touch the class yet :)

I have a question, however:

What is the use of using { brackets in the while loop?

instead of



while($r = mysql_fetch_assoc($q)){
echo "{$r['id']},{$r['name']}<br />";
}


following runs just fine here:



while($r = mysql_fetch_assoc($q)){
echo "$r['id'],$r['name']<br />";
}



I'm asking this because I had to use the value in a function for exp:



MyFunction ({$r['id']});


and obviously got an error and used



MyFunction ($r['id']);


instead and it run fine.

guvenck
02-03-2006, 03:28 AM
Oh, and forgot to mention,

1- what about adding Previous and Next links?
2- First and Last are not displayed here. What am I missing? I replaced the code to



echo $pager->get_range('<a href="{LINK_HREF}">{LINK_LINK}</a>',' &raquo ','İlk Sayfa','Son Sayfa').'<br /><br />';


How do request them?

firepages
02-03-2006, 03:55 PM
following runs just fine here:
echo "$r['id'],$r['name']<br />";


that should give a parse error in php4 and 5, .. though whilst ..
echo "$r[id],$r[name]<br />"; //no single quotes
would not give an error, neither would it parse the array values properly..

The braces tell PHP that the enclosed data is an array (or other) value and to parse it as such , it also works with class variables ..
echo "hello from {$this->name}"; etc

As for first and last links, they should work if you have enough results. They won't show if your number of pages is leass than set_range() .. you also need to be using $pager->set_range($int); for it to work at all.

If thats not the problem please post again!

firepages
02-03-2006, 03:57 PM
ah ok sorry missed point 1, previous and next ... will add something tomorrow.

guvenck
02-03-2006, 05:23 PM
This is how I use it:



<?php

function DoTwoDigits($val) {
if (intval($val) < 10) {
$twodigits = "0$val";
}
elseif (intval($val) >= 10) {
$twodigits = $val;
}
echo $twodigits;
}


/* Lots of code here */



while ($r = mysql_fetch_assoc($q)) {
DoTwoDigits($r['fday']);
echo ".";
DoTwoDigits($r['fmonth']);
}

?>

Rich Pedley
02-03-2006, 08:57 PM
didn't I already mention previous/next?

Actually a thought with this, any chance of being able to create separated previous and next links?

$pager->get_nextlink
$pager->get_previouslinkWhich could be added elsewhere on the page (though obviously they should be able to be set to automatically appear by the page numbers as well.

Don't know how possible this is though.

Squid
02-06-2006, 12:39 PM
So I'm using this class, it works great, thanks for submitting it. Only question I've got is, when I am on page 8 for example, you can still click on it. I wish for it to be a text value instead of a link. Is this possible in this class?

Thanks in advance.

Rich Pedley
02-07-2006, 12:23 AM
After having used this class for a while I have finally noticed a wee mistake - not in the class but in your suggested usage:

&raquo should in fact be:
&raquo;
The semi-colon making all the difference :-)

guvenck
02-09-2006, 02:50 AM
firepages, any improvements about "previous" and "next" features? I look forward to seeing it, fingers crossed :)

firepages
02-11-2006, 03:47 AM
Hi , yes .. added

$pager->get_prev('<a href="{LINK_HREF}">Prev</a>');
$pager->get_next('<a href="{LINK_HREF}">Next (text or image etc)</a>');

this introduced a new internal function _get_qurl() which altered get_range() so if you are using a modified version check for those changes first.

Rich Pedley
02-11-2006, 05:22 PM
good news, thanks for the update!

firepages
02-18-2006, 03:30 PM
Another change ... when using get_range() display was borked ~
Also added get_offset_limit(); (returns the current offset , we already know what $num is) since some databases don't support `LIMIT $offset , $num`.
+ a real example here (http://www.firepages.com.au/pagination.htm)

Rich Pedley
02-24-2006, 03:20 PM
for($x=$min; $x<=$to; ++$x){
$rets[]=str_replace($this->_l_tpls, array($pre_url.$x, $x) , $format);
}

By amending those lines to this:

for($x=$min; $x<=$to; ++$x){
if($x!=$this->curr){
$rets[]=str_replace($this->_l_tpls, array($pre_url.$x, $x) , $format);
}else{
$rets[]=$x;
}
}
The current page number is not returned as a link.

ns1987
03-04-2006, 02:42 AM
Looks pretty good, kind of large, though. =/

gilligans
03-23-2006, 12:05 AM
Hi ,

The pagination works fine except the view all part.
Please help. i think i must be doing some silly mistake.
following is the code.


<?php
include('/mySqlConnection.php');
include('/mysql/pagination.php');
$ObjConnection=new mySqlConnection();

//Check if Table Existance (Return True if Exists otherwise False).
$TableName="historyParsed_output";
$ObjConnection->DataBaseTableExists($TableName);


$max = mysql_result( mysql_query("SELECT COUNT(*) FROM stock _discussion"), 0 ) ;

if(isset($_GET['view']))$records=$max;

$pager = new pager(
$max , /*see above*/
10 , /*how many records to display at one time*/
@$_GET['_p'] /*this is the current page no carried via _GET*/
) ;


$pager->set_range(10);

$SelQuery ="SELECT * FROM stock _discussion LIMIT ".$pager->get_limit();


$queryResource=mysql_query($SelQuery);


echo $pager->get_title('Page {CURRENT} of {MAX}<br />Displaying results {FROM} to {TO} of {TOTAL}'). ' <br />';


echo '<div class="paginate">';
if($pager->_pages >= 2){
echo $pager->get_title('Viewing page {CURRENT} of {MAX}<br />Displaying results {FROM} to {TO} of {TOTAL}'). ' <br />';
}else{
echo $pager->get_title('Viewing page {CURRENT} of {MAX}'). ' <br />';
}

echo $pager->get_range('<a href="{LINK_HREF}">{LINK_LINK}</a>',' &raquo; ','First','Last').'<br />';

if($pager->_pages >= 2){
echo '<a href="'.$_SERVER['PHP_SELF'].'?view=all">View all</a>';
}
echo '</div>';


/*+ of course the actual data*/
while($r = mysql_fetch_assoc($queryResource)){
echo "{$r['stockID']},{$r['httpLink']}<br />";
}




Please help.
Thx,
gilligans

Rich Pedley
03-23-2006, 11:12 AM
what error, if any do you get?

(remember when posting php to use the [ php ] tags)

w3bs-otsu
06-06-2006, 02:31 PM
This may be steppin on toes here but this is what I use and although I haven't tried the extensive class posted prior I thought I would put my version up for ridicule.


if (isset($_GET['pageno'])) {
$pageno = $_GET['pageno'];
} else {
$pageno = 1;
} // if

$query = "SELECT COUNT(*) FROM `my_table` WHERE `foo` = '$bar' ";
$result = mysql_query($query);
$numrows = mysql_num_rows($result);
if ($numrows == 0) {

$page.='No results found.';

} else {

$rows_per_page = 10; // edit or globalise etc to display number results per page

$lastpage = ceil($numrows/$rows_per_page); // get last page

$pageno = (int)$pageno;
if ($pageno < 1) {
$pageno = 1;
} elseif ($pageno > $lastpage) {
$pageno = $lastpage;
} // if

$limit = 'LIMIT ' .($pageno - 1) * $rows_per_page .',' .$rows_per_page;

$sql2 = "SELECT * FROM `my_table` WHERE `foo` = '$bar' ORDER BY `foo` ASC $limit";



And then your query results here ------




// Start of pagination display - either above or below result set or both

if ($pageno == 1) {
$page.=" FIRST PREV ";
} else {
$page.=" <a href='{$_SERVER['PHP_SELF']}?pageno=1'>FIRST</a> ";
$prevpage = $pageno-1;
$page.=" <a href='{$_SERVER['PHP_SELF']}?pageno=$prevpage'>PREV</a> ";
} // if

$page.="&nbsp;( Page $pageno of $lastpage )&nbsp;";

if ($pageno == $lastpage) {
$page.=" NEXT LAST ";
} else {
$nextpage = $pageno+1;
$page.=" <a href='{$_SERVER['PHP_SELF']}?pageno=$nextpage'>NEXT</a> ";
$page.=" <a href='{$_SERVER['PHP_SELF']}?pageno=$lastpage'>LAST</a> ";
} // if

$pages = $lastpage + 1;

$page.='<p align="center">PAGES ';

for($i=1; $i<$pages; $i++):

if($i == $pageno) {

$page.="-&nbsp;".$i."&nbsp;";

} else {

$page.="-&nbsp;<a href='{$_SERVER['PHP_SELF']}?pageno=".$i."'>".$i."</a>&nbsp;";

}

endfor;

$page.='- </p>';

}



For those of you who have used the previous pagination class, what aspects does this version not have in comparison - feedback required.

firepages
06-06-2006, 04:25 PM
There is probably little if anything the class can do that your code does not do, but thats not really the point of using a class.

The main point of using classes (or even functions) is to try and create re-usable code , with a class that is generic enough you can reuse it in many different applications.

It is true that copy-&-paste is code reuse, but lets say I decide to use your code in one of my applications... lets imagine also that the $page variable already exists in the global scope in my app (quite possible!) .. we have to start renaming variables.. not once but several times.

Its nearly as simple as that, I can reuse the class wherever without worrying too much about stuff like that, I can paginate an existing script I have never seen before in a couple of minutes & to me that makes it worth while.

I am not trying to pretend that my class is the best implementation of such a script, far from it, and there is nothing wrong with your script as is.. but despite the end result they are 2 different things and you can't really compare them as such.

w3bs-otsu
06-07-2006, 01:54 PM
you da man firepages - couldn't have put it better myself.

I am all for duplication.

$duplication - $hassle = $bliss;

:D

cheryl
06-09-2006, 06:51 PM
hi! i have a table which displays i list of records. records can be many, and i would like to limit a page to only showing 50 records at once, & have links to be able to go view the next 50 records and so on.

how should i use the pagination class to limit and "create" the sbusequent link pages?

attached is the file that displays the records.

please assist. thanks.

firepages
06-10-2006, 03:54 AM
without having the DB to test I cant check for parse errors etc... but at line 118/119 change to ...


<?php
include_once 'pager.class.php';
$selectsql=str_replace('*', 'COUNT(1)', $selectsql);
$max=mysql_query($selectsql);
$num=50;
$pager = new pager( $max, $num, @$_GET['_p']);

$selectlist_result=mysql_query($selectsql.' LIMIT '.$pager->get_limit());
or die ("Couldn't execute query.".mysql_error()."".$selectsql);
/*if it worked ...*/
echo $pager->get_title('Page {CURRENT} of {MAX}<br />Results {FROM} to {TO} of {TOTAL}');

?>


try that and tell me what happens

cheryl
06-10-2006, 07:56 AM
without having the DB to test I cant check for parse errors etc... but at line 118/119 change to ...


<?php
include_once 'pager.class.php';
$selectsql=str_replace('*', 'COUNT(1)', $selectsql);
$max=mysql_query($selectsql);
$num=50;
$pager = new pager( $max, $num, @$_GET['_p']);

$selectlist_result=mysql_query($selectsql.' LIMIT '.$pager->get_limit());
or die ("Couldn't execute query.".mysql_error()."".$selectsql);
/*if it worked ...*/
echo $pager->get_title('Page {CURRENT} of {MAX}<br />Results {FROM} to {TO} of {TOTAL}');

?>


try that and tell me what happens


okie.. i've copied and pasted the class as pager.class.php

after which line of code should i put the include_once("pager.class.php"); ?

then where do i put the remaining codes?

do i still need sql statements that selects the data??

also, i have the sort and filter if,else statements. would it affect the displaying of 50 records per page??

please assist. i'm a programming dumbo.

DragonI
08-06-2006, 07:52 PM
Great Class, firepages. I've tested it out and it works most excellently :thumbsup:

I would like to add an "onclick" to your pager class in order to perform Ajax pagination. Any suggestions on how I would go about doing that?

The onclick would look something like:
onclick="getSearchResults($parm1, $parm2, $pageNumber)"

mudogg80
09-27-2006, 05:04 PM
Great class! works very well, but i have one question:
I can't figure out how to highlight the page your currently on for example:
1 | 2 | 3 | 4 , is there anyway to do this??

Thanks

firepages
10-09-2006, 04:51 PM
if you change the last few lines to this ...



<?
for($x=$min; $x<=$to; ++$x){
$rets[]=($this->curr!=$x)?str_replace($this->_l_tpls, array($pre_url.$x, $x) , $format):$x;
}
?>


then the active page does not get linked which in itself is a sort of highlight (at least it looks different) ... I prefer to use the get_title() function to make the selected page obvious though I suppose the current page need not be a link.

mudogg80
10-30-2006, 07:05 PM
Everything is working great! I have another quick question, Currently I display the pagination as:
prev | 4 | 5 | 6 | 7 | next

How can I create a display similar to the following with your class:
ex:
view all | first page | previous page | 4 | 5 | 6 | next page | last page

Any suggestions?
Thanks!!!

mudogg80

jaguar
04-23-2007, 11:09 PM
I am a complete newbie to php. I have added the pager.class.php to my server and implemented the code into my page. I get the proper TEXT results, so the script is working as expected. What I need to do, however, is have clickable links and I'm curious how to make that happen.

These lines of code:

while($r = mysql_fetch_assoc($q)){
echo "<div> {$r['title']}</div>";
echo "<div> {$r['link']}</div>";
}

Return something similar to:

Joe's Bar and Grill
.http://www.joesbarandgrill.xxx.

How do I make the title a clickable link?

Any help would be greatly appreciated.

firepages
04-24-2007, 12:16 AM
<?php
while($r = mysql_fetch_assoc($q)){
echo "<div><a href="{$r['link']}">{$r['title']}</a></div>";
}
?>

jaguar
04-24-2007, 02:22 AM
Interesting. Thats what I thought. I actually tried this earlier

I tried this again and still get this error

Parse error: syntax error, unexpected '{', expecting ',' or ';' in /home4/xxxx/xxx.com/public_html/linkd/pages/xxx.php on line 25


Line 25 being the line containing this code:

echo "<div><a href="{$r['link']}">{$r['title']}</a></div>";
}


If I remove the "{}" in {$r['link']}, I get this error. Parse error: syntax error, unexpected T_VARIABLE, expecting ',' or ';' in ..... Line 25

Thanks for your prompt reply.

P.S. My server is running PHP Version 5.2.1

jaguar
04-26-2007, 08:49 PM
Okay. I worked it out after visiting some other forums.

The correct syntax is:

<?php
while($r = mysql_fetch_assoc($q)){
echo "<div><a href='{$r['link']}'>{$r['title']}</a></div>";
}
?>

Single quotes (') instead of double quotes (") in the href statement.
Thanks again for your help.

iLLin
04-27-2007, 07:47 AM
You could of commented the double quotes like so:


<?php
while($r = mysql_fetch_assoc($q)){
echo "<div><a href=\"{$r['link']}\">{$r['title']}</a></div>";
}
?>

jaguar
04-30-2007, 12:31 AM
Thanks. Does it make a difference operationally? This is for future reference.

jaguar
04-30-2007, 12:32 AM
You could of commented the double quotes like so:


<?php
while($r = mysql_fetch_assoc($q)){
echo "<div><a href=\"{$r['link']}\">{$r['title']}</a></div>";
}
?>


Thanks. Does it make a difference operationally? This is for future reference.

Len Whistler
05-01-2007, 02:31 AM
Does anyone have this pagination class working on a website? If so please post a link, I would like to see how it looks. Thanks

firepages
05-01-2007, 01:59 PM
Hi, there is a small example on my site @ http://www.firepages.com.au/pagination.htm , but how it looks it totally up to you & thats really the point of the class and allows it to be reused anywhere since no markup is hardcoded in

firepages
05-05-2007, 04:05 PM
ok , here's an example in flash ...

http://www.jdstudio.com.au/shine.php/search/pendants

ok flash still has to dynamically display the page numbers and links but the class passes all the relevant information .. had to add $pager->set_from and $pager->set_to to make flash aware of the true star and finish pages when using set_range.

The advantage is that I did not have to rewrite a pager just for this deployment , simply echoed out the class variables to flash....e.g.....


<?php
include_once FPA_LIB.'/lib/pager.class.php';

$max=mysql_result(
mysql_query("SELECT count(gv_i_id) FROM fpa_gallery_virtual WHERE gv_gvc_id='{$_REQUEST['gv_gvc_id']}'"),0);

$pager = new pager( $max, 10, @$_GET['_p']);
$pager->set_range(10);

$sql = "SELECT gv_i_id, i_id, LEFT(i_desc,50) as i_desc, i_title, i_path
FROM fpa_gallery_virtual
LEFT JOIN fpa_gallery_img
ON gv_i_id=i_id
WHERE gv_gvc_id={$_REQUEST['gv_gvc_id']} LIMIT ".$pager->get_limit() ;

$q = mysql_query($sql) ;
while($r = mysql_fetch_assoc($q)){
$path[]=urlencode($r['i_path']);
$title[]=urlencode($r['i_title']);
$desc[]=urlencode($r['i_desc']).'....';
$id[]=urlencode($r['gv_i_id']);
}
#required to make sure that set_to & from are initialized
$ignore = $pager->get_range('','');

#for flash consumption
echo 'res='.$max.'&i_path='.implode(':', $path).'&i_title='.implode(':', $title).'&i_desc='.implode(':', $desc).'&i_id='.implode(':', $id)."&_pages={$pager->_pages}&_from={$pager->_from}&_to={$pager->_to}&_total={$pager->_total}&_curr={$pager->curr}&_set_from={$pager->set_from}&_set_to={$pager->set_to}";
?>

Len Whistler
05-06-2007, 11:26 PM
Hi, there is a small example on my site @ http://www.firepages.com.au/pagination.htm , but how it looks it totally up to you & thats really the point of the class and allows it to be reused anywhere since no markup is hardcoded in


The hex color example looks very good. Thanks

ClammyDoo
05-20-2007, 03:50 AM
Am i the only one who cannot get this to work? lol

Jim Nayzium
07-20-2007, 06:57 PM
I currently use the lame paging with the include Dreamweaver codes. This class is MAGNIFICIENT!!! I love it!!!

WARNING: THIS IS well thought out post, and long. However, you may find the results very useful if you ever need to use drop-downs to filter a page results and keep those results consistent while utilizing this class.

Therefore, I believe it is worth reading my post. I know forums are filled with morons (usually ones like me...) ranting on and on. Well I am sorry for the length, but it is packed with useful information to help you solve my problem, and possibly provide a good on-going solution for future use.

Thanks for your time in advance. It is much appreciated!


I have a page which uses drop downs to filter the search results which uses javascript to keep the results persistent.

Here is the page in Question
CLICKIE (http://www.studioauditions.com/industrynews_home_paging.php)

I have successfully gotten the paging class to recognize that I have 579 records and it makes the proper paging show up on the page, but because of my javascript and the necessary _GET variables, the pages don't persistently hold on to the submitted information, and therefore cause the class.pager to not work -- meaning, the clickies always take you to the first page's results even though the class thinks otherwise.

What is cool though is the javascript is being useful to the class, because if you do filter the page using my javascript scripts and click the GO button, the class recognizes the difference in the findings. Notice the change in the number of pages and record count.

I have a feeling I can probably lose all my javascript to make it somehow persistent utilizing just the class....who knows really....but the php that generates the page is complex enough that I am not looking for best-practice, I am looking for best-FIX....seriously.

Here are the _GET variables that keep my world persistent currently


?pageNum_rsWritings=1&maxRows_rsWritings=10&totalRows_rsWritings=579&_p=4&selectWritingCat=0&selectManuf=0&selectDate=0

Or more elegantly for those willing to help code up something for me
(Filled with sample values from the second page when the current NEXT link is clicked at the bottom of the page.)


pageNum_rsWritings=1
maxRows_rsWritings=10
totalRows_rsWritings=579
selectWritingCat=0
selectManuf=0
selectDate=0

Also, Noteworthy -- my pageNum_rsWritings is really doing what the _p variable is doing in the class, however, mine is array based, so when _p would equal 1, mine equals 0.

So long story longer, what I need is a way to echo the links to the page, but have the the submitted links, when clicked, (the page numbers inside the class deployment that is) carry forward the above mentioned _GET URL variables in them.

Below is the javascript that you could view in the page if you viewed source.

function GetFilters() {
rtnString = "selectWritingCat=" + document.form1.selectWritingCat.value + "&selectManuf=" + document.form1.selectManuf.value + "&selectDate=" + document.form1.selectDate.value;
return rtnString;
}

function FilteredPaging(url, paging) {
if (document.form1.filterChanged.value == "true") {
window.location = url + "?" + GetFilters();//CHANGED HERE
} else {
window.location = url + "?" + paging + "&" + GetFilters(); // CHANGED HERE
}
}

function ReloadPage(url) {
window.location = url + "?" + GetFilters();
}

And below is the php code that currently makes the HACKY Dreamweaver generated NEXT link actually work.

<a href="javascript:FilteredPaging('<?php echo $currentPage; ?>','<?php printf("pageNum_rsWritings=%d&maxRows_rsWritings=%d%s", min($totalPages_rsWritings, $pageNum_rsWritings + 1), $maxRows_rsWritings, $queryString_rsWritings); ?>')">Next</a>

Right now, if you filter the page, it holds onto the values it needs. But when you click the number links from the class, it submits the _GET variables that hold the manufacturer and category, but the _p=2 code is for some reason not recognized.

The code that would be great to add, but I don't understand how to alter the {LINK_LINK} variables, would be to in addition to the _p appended to the URL value...

another _GET variable is added which would be equal to

_p - 1 : due to my array difference...meaning, my zero page equals the class's 1 page.

So --- if you manually past in the address bar the pageNum_rsWritings=(whatever the _p - 1 value would be) it goes to the right page!

So the real question is HOW do I append that the string URL that gets submitted?


Again, I would like to say that this class is RE-Donkulously perfect for my needs and I absolutely love it.

I am sincerely hopeful that what I am asking is understandable and helps someone else out when we find the solution.

Working together we can solve world hunger! Or maybe just help some audio-phyles find their articles faster....either way I am happy.

Jim Nayzium
07-20-2007, 10:18 PM
OK...

Pretty sure I have fixed it in a round-a-bout way. Thought I would post this here to help anyone that read my whole post.

Also, I have a feature request but will separate that off in another reply.

My solution is pretty dependent on my current situation with my current code, but I would hate to have posted such a long situation and then not provided my answer.

I have code that determines the starting row already present in my current paging...but the current paging only gave Next Previous Last End...not page numbers...

So, I wrote logic that detects if _p is set or not. If so, I needed to subtract ONE from it, as the array needed to match....meaning, my first page was array[0] not 1....

So I in essence, passed a new fake value to my already existing RecordToStartWith variable...that was equal to _p minus 1 X the number of maxRows allowed.

therefore, I leveraged all the code I had in place already to maintain the persistency of the javascript pulldown filtering...and got to use this wonderfully elegant paging class also!!!

six hours of my life I will never get back, but you live and learn!

Jim Nayzium
07-20-2007, 10:20 PM
OK, feature request...

I have one list with 58 pages...

Would love it to say...

First 2 3 4 5 . . . 22 23 24 . . . 55 57 58 LAST

I think I could do this by deploying more than one instances of the class with differing ranges...

but man, this is so elegant as is...was just wondering if there were a more OOP savvy programmer working on it if it would be a simple addition or not...

THANKS

Jim Nayzium
07-20-2007, 11:40 PM
I also just added a drop down menu that has each page in it...built dynamically from the MAX and selects the CURRENT values.


<?php
//find out the size of our recordset , only fetch a count, in this query nothing else
$max = $totalRows_rsWritings; /* COMMENT OUT THE PASTED PORTION and subbed in Mine from included file writings_home_code.php (included above)mysql_result( mysql_query("SELECT COUNT(id) FROM table WHERE id > 0"), 0 ) ;*/
$pager = new pager(
$max , /*see above*/
10 , /*how many records to display at one time*/
@$_GET['_p'] /*this is the current page no carried via _GET*/
) ;

/*
optionally set a maximum number of pages to display
so you dont end up with 100's of links
*/
$pager->set_range(10);

/*the main query note the same WHERE conditions*/
$q = mysql_query($totalRows_rsWritings/*AGAIN COMMENT OUT THIER CODE "SELECT id,name FROM table WHERE id > 0 LIMIT "*/.$pager->get_limit());

/*show something for your troubles*/
echo $pager->get_title('Page&nbsp;{CURRENT}&nbsp;of&nbsp;{MAX}<br /><br />Displaying&nbsp;results&nbsp;{FROM}-{TO}&nbsp;of&nbsp;({TOTAL})'). '<br /><br />';

echo $pager->get_range('<a href="javascript:FilteredPagingForPagerClass(\''.'{LINK_HREF}\')">{LINK_LINK}</a>',' &raquo ','First','Last');
//these could also be images/anything '<img src="first.jpg" />' etc //these could also be images/anything '<img src="first.jpg" />' etc
echo "<br /><br />";
echo $pager->get_prev('<a href="{LINK_HREF}">&laquo;&laquo;&nbsp;Prev</a>&nbsp;&nbsp;');

$looper_value_length = $pager->get_title("{MAX}") ;

?>
<select name="page_selector" onchange="SelectListReloadPage(this.options[this.selectedIndex].value)">
<?php
for ($looper = 1; $looper <= $looper_value_length; $looper++) { ?>
<option value="<?php echo $currentPage.'?'.'_p='.$looper;?>" <?php if ($pager->get_title("{CURRENT}") == $looper) { echo 'selected="selected"'; } else echo ""; ?>>Page&nbsp;<? echo $looper;?></option>
<?php } ?>
</select>
<?php

echo '&nbsp;&nbsp;';
echo $pager->get_next('<a href="{LINK_HREF}">Next &nbsp;&raquo; &raquo;</a>');




echo "<br />";



?>

The Javascript call on the onchange event is


function GetFilters() {
rtnString = "selectWritingCat=" + document.form1.selectWritingCat.value + "&selectManuf=" + document.form1.selectManuf.value + "&selectDate=" + document.form1.selectDate.value;
return rtnString;
}

function FilteredPaging(url, paging) {
if (document.form1.filterChanged.value == "true") {
window.location = url + "?" + GetFilters();
} else {
window.location = url + "?" + paging + "&" + GetFilters();
}
}


//MSS function altered...here
function FilteredPagingForPagerClass(paging) {
if (document.form1.filterChanged.value == "true") {
window.location = paging+GetFilters();//CHANGED HERE
//alert("Get Filters + paging: " + paging + "&" + GetFilters());
} else {
// alert("paging only: " + paging)
window.location = paging; // CHANGED HERE
}
}


function SelectListReloadPage(url) {
window.location = url +"&"+GetFilters();
}

mhunt
09-17-2007, 05:45 PM
fixed

Fumigator
11-01-2007, 08:00 AM
Firepages:

Your website seems to be missing the source for this class. Was it removed on purpose? I don't want to distribute it if you no longer want to make it available.

This page contains no code (http://firepages.com.au/php_pagination_class.htm)

fishnyc22
11-08-2007, 10:18 PM
Hey guys. Loving this code. Thanks for putting it together FirePages. Quick question. I'm having link problems. it seems that the "&amp;" in the class is causing my URLS to actually be written with &amp; instead of & thus causing php not to find the _p properly.

Any idea whats up? any help is appreciated.

fishnyc22
11-08-2007, 11:35 PM
Hey guys, seem that this code was causing the problem for me:



function _get_qurl()
{
$q = empty($this->_req_qs) ? '' : '?'.$this->_req_qs ;
$s = (substr($q, 0, 1) == '?') ? '&amp;' : '?' ;
return $this->_req_url . $q . $s . $this->_ctl . '=';
}


It was causing the strings in the url to have &amp;amp; in it. which is just not good. so I changed the '&amp;' to '&' and all is well in the world

Looking good now though. thanks.

One Question. Say I have 5 page numbers shown at a time like this (assuming I have 10 pages)

1 2 (3) 4 5

And if I goto page 5 i see

1 2 3 4 (5)

but I would prefer to see

3 4 (5) 6 7

Any way to do that?

Thanks again

afe
12-02-2007, 08:38 PM
Is there a demo of it?

fishnyc22
05-09-2008, 08:41 PM
Hey gang, I'm getting this error in my logs whenever the page loads:

PHP Fatal error: Call to a member function on a non-object in /var/www/vhosts/mydomain.com/index.php on line 237, referer: http://www.mydomain.com/

This is the code on that page. Line 237 is the first line below. Any idea whats causing it.

Thx



echo $pager->get_title('Page {CURRENT} of {MAX}'). '<br />';
echo $pager->get_prev('<a href="{LINK_HREF}">Prev</a> ');
echo $pager->get_range('<a href="{LINK_HREF}">{LINK_LINK}</a>',' ', 'First',' Last');
echo $pager->get_next(' <a href="{LINK_HREF}">Next</a>');

Sylvester21
05-20-2010, 10:45 PM
One Question. Say I have 5 page numbers shown at a time like this (assuming I have 10 pages)

1 2 (3) 4 5

And if I goto page 5 i see

1 2 3 4 (5)

but I would prefer to see

3 4 (5) 6 7

Any way to do that?

Thanks again

I am wondering the same thing :)

Can anyone help with this?