TalkPHP
 
 
Account Login
Latest Articles
» The basic usage of PHPTAL, a XML/XHTML template library for PHP
» Vulnerable methods and the areas they are commonly trusted in.
» Simple way to protect a form from bot
» The Basics On: How Session Stealing Works
» How to keep your forms from double posting data
IRC Channel
IRC Speech Bubble Join the friendly bunch on IRC...
(#TalkPHP on Freenode)

...Also available via a web interface.

See this thread for information on the TalkPHP Free Hugs Initiative™. Subject to availability.
Associates
Associates
CSS Tutorials
Reply
 
LinkBack (3) Thread Tools Search this Thread Display Modes
Old 12-07-2007, 05:48 PM   3 links from elsewhere to this Post. Click to view. #1 (permalink)
The Addict
Upcoming Programmer Top Contributor 
 
Rendair's Avatar
 
Join Date: Nov 2007
Location: UK
Posts: 319
Thanks: 18
Rendair is on a distinguished road
Default Advance Pagination Class

Hey all, well i thought i would now write a advance pagination. After racking my brain for awhile i finally figured out a nice class script for creating one.

This class will display the results of any MySQL table including all the fields and rows. It will work out how many fields there are and display the results accordingly.

You can view a demo HERE

When changing the table in the demo if you change to CD list and go through them it like pressing number 2 or next it will go back to DVD's as this is a class tutorial. Was mainly to show you that it works

Start:
PHP Code:
class pagination{


Firstly we need to get up some variables.

PHP Code:
var $p=1$max_r,$limits;
var 
$count_all=0,$sql,$total,$table,$totalres,$totalpages;
var 
$r,$i;
var 
$show=10
Now we need to start setting up some functions. First one of course is our MySQL connect function

PHP Code:
function connect($host,$username,$password,$name){
  
$connectect mysql_connect($host$username$password) or die(mysql_error());
  
$selected mysql_select_db($name) or die(mysql_error());

Now we have done that we need to create a function to set the maxium number of posts to be displayed on each page. I have also included working out the limits and maximum values ready for the query.

PHP Code:
function setMax($max_r){
                 
   
$this->$_GET['p'];
   
$this->max_r $max_r;
            
    if(empty(
$this->p))
    {
         
$this->1;
    }
            
   
$this->limits = ($this->1) * $this->max_r;


Now that we have done that we can start with the quires and setting the data.

PHP Code:
function setData($table){
                    
   
$this->table $table;
   
$this->sql "SELECT * FROM ".$this->table." LIMIT ".$this->limits.",".$this->max_r."";
   
$this->sql mysql_query($this->sql) or die(mysql_error());
   
$this->total "SELECT * FROM ".$this->table."";
   
$this->totalres =  mysql_query($this->total) or die(mysql_error());
   
$this->count_all mysql_num_rows($this->totalres); // count all the rows
   
$this->totalpages ceil($this->count_all $this->max_r); // work out total pages 

Ok now comes the interesting and clever part. We now need to display the table. There are a couple of things we need to take into account here. We need to know how many fields there are in the table we are using and also how many rows and display them nicely.

PHP Code:
function display(){

echo 
"<b>Total Values(s):</b>".$this->count_all."<br><br>";
                  
echo 
"<b>Page:</b> ".$this->p."<br>";
    
$fields=mysql_num_fields($this->totalres); // workout number of fields
                        
                        
echo "<table border=1 width=100%><tr>";

  for (
$i=0$i mysql_num_fields($this->sql); $i++) //Table Header
  

     print 
"<th>".mysql_field_name($this->sql$i)."</th>"//display field name
  
}
     echo 
"</tr>";
  while (
$row mysql_fetch_row($this->sql)) 
  { 
     echo 
"<tr>";
    for (
$f=0$f $fields$f++) 
    {
       echo 
"<td>$row[$f]</td>"
    }
  echo 
"</tr>\n";
  }
  echo 
"</table><p>";
                 

Now all we want to do now is display the links.

PHP Code:
 function displayLinks($show){
                
    
$this->show $show// How many links to show
        
    
echo "<br><br>";
           
    if(
$this->1// If p > then one then give link to first page
    
{
        echo 
"<a href=?p=1> [FIRST] </a>  ";    
    }
        else
        { 
// else show nothing
            
echo "";
    }
    if(
$this->!= 1)
        { 
// if p aint equal to 1 then show previous text
                  
            
$previous $this->p-1;
        echo 
"<a href=?p=$previous> [ PREVIOUS ] </a>";
                        
    }
    else
        { 
//else show nothing
        
echo "";
    } 
    for(
$i =1$i <= $this->show$i++) // show ($show) links
    
{
                     
            if(
$this->$this->totalpages)
                { 
// if p is greater then totalpages then display nothing
                
echo "";
        }
        else if(
$_GET["p"] == $this->p)
                { 
//if p is equal to the current loop value then dont display that value as link
                   
echo $this->;
        }
        else{
                   echo 
" <a href=?p=".$this->p."> ( ".$this->p.") </a>"// else display the rest as links
        
}
            
        
$this->p++; //increment $p  
    
}
    echo 
"....."// display dots
                    
    
if($_GET["p"] == $this->totalpages)
        {
// if page is equal to totalpages then  dont display the last page at the end of links
        
echo "";
    }
    else 
// else display the last page link after other ones
    
{
        echo 
"<a href=?p=".$this->totalpages."> ( ".$this->totalpages.") </a>"
    }
    if(
$_GET["p"] < $this->totalpages)// if p is less then total pages then show next link
    
{
        
$next $_GET["p"] + 1;
        echo 
"<a href=?p=$next> [ NEXT >] </a>";    
    }
                  
    echo 
"<br><br>";


Thats the class now finished. All we want to do now is start displaying it and creating the instance.

PHP Code:
$page= new pagination;
$page->connect("host","username","password","dbname");
$page->setMax(25);      // 25 being number of results to be displaued
$page->setData("tablename");
$page->display();
$page->displayLinks(5); // 5 being number of links to display 
This is my brushing up on my classes haha.

Full CODE:

PHP Code:
<?php

    
class pagination{
    
            var 
$p=1$max_r,$limits;
            var 
$count_all=0,$sql,$total,$table,$totalres,$totalpages;
            var 
$r,$i;
            var 
$show=10;

            function 
connect($host,$username,$password,$name){
                
                
$connectect mysql_connect($host$username$password) or die(mysql_error());
                
$selected mysql_select_db($name) or die(mysql_error());
            }
        
            function 
setMax($max_r){
                 
                  
$this->$_GET['p'];
                  
$this->max_r $max_r;
            
                      if(empty(
$this->p))
                      {
                        
$this->1;
                      }
            
                  
$this->limits = ($this->1) * $this->max_r;

            }    
            
            function 
setData($table){
                    
                  
$this->table $table;
                  
$this->sql "SELECT * FROM ".$this->table." LIMIT ".$this->limits.",".$this->max_r."";
                    
$this->sql mysql_query($this->sql) or die(mysql_error());
                  
$this->total "SELECT * FROM ".$this->table."";
                  
$this->totalres =  mysql_query($this->total) or die(mysql_error());
                  
$this->count_all mysql_num_rows($this->totalres);
                  
$this->totalpages ceil($this->count_all $this->max_r);
            }
            
            function 
display(){

                  echo 
"<b>Total Values(s):</b>".$this->count_all."<br><br>";
                  
                  echo 
"<b>Page:</b> ".$this->p."<br>";
    
                    
$fields=mysql_num_fields($this->totalres);
                        
                        
                      echo 
"<table border=1 width=100%><tr>";
                        for (
$i=0$i mysql_num_fields($this->sql); $i++) //Table Header
                        

                            print 
"<th>".mysql_field_name($this->sql$i)."</th>"
                        }
                        echo 
"</tr>";
                        while (
$row mysql_fetch_row($this->sql)) 
                        { 
                            echo 
"<tr>";
                            for (
$f=0$f $fields$f++) 
                            {
                                echo 
"<td>$row[$f]</td>"
                            }
                            echo 
"</tr>\n";
                        }
                        echo 
"</table><p>";
                 
            }
            
            function 
displayLinks($show){
                
                  
$this->show $show// How many links to show
        
                   
echo "<br><br>";
           
                  if(
$this->1// If p > then one then give link to first page
                  
{
                        echo 
"<a href=?p=1> [FIRST] </a>  ";    
                  }
                  else{ 
// else show nothing
                        
echo "";
                  }
                  if(
$this->!= 1){ // if p aint equal to 1 then show previous text
                  
                          
$previous $this->p-1;
                          echo 
"<a href=?p=$previous> [ PREVIOUS ] </a>";
                        
                  }
                  else{ 
//else show nothing
                          
echo "";
                  } 
                  for(
$i =1$i <= $this->show$i++) // show ($show) links
                  
{
                     
                        if(
$this->$this->totalpages){ // if p is greater then totalpages then display nothing
                            
echo "";
                        }
                        else if(
$_GET["p"] == $this->p){ //if p is equal to the current loop value then dont display that value as link
                            
echo $this->;
                        }
                        else{
                            echo 
" <a href=?p=".$this->p."> ( ".$this->p.") </a>"// else display the rest as links
                        
}
            
                        
$this->p++; //increment $p  
                  
}
                    echo 
"....."// display dots
                    
                   
if($_GET["p"] == $this->totalpages){// if page is equal to totalpages then  dont display the last page at the end of links
                            
echo "";
                   }
                   else 
// else display the last page link after other ones
                   
{
                        echo 
"<a href=?p=".$this->totalpages."> ( ".$this->totalpages.") </a>"
                   }
                   if(
$_GET["p"] < $this->totalpages)// if p is less then total pages then show next link
                   
{
                        
$next $_GET["p"] + 1;
                        echo 
"<a href=?p=$next> [ NEXT >] </a>";    
                   }
                  
                   echo 
"<br><br>";

            }
        
    }

$page= new pagination;
$page->connect("host","username","password","dbname");
$page->setMax(25);
$page->setData("tablename");
$page->display();
$page->displayLinks(5);
}

?>
__________________
www.jooney.co.uk - the online portfolio
Send a message via MSN to Rendair
Rendair is offline  
Reply With Quote
The Following 3 Users Say Thank You to Rendair For This Useful Post:
Gurnk (12-07-2007), Nor (12-13-2007), Wildhoney (12-07-2007)
Old 12-07-2007, 08:49 PM   #2 (permalink)
bdm
The Acquainted
Good Samaritan 
 
Join Date: Nov 2007
Posts: 127
Thanks: 14
bdm is on a distinguished road
Default

Nice approach.

Note that I'm not an OOP wizard, but hopefully these tips will help you and if someone disagrees, let me know.
- What version of PHP are you using? Because I've noticed that you're still using the var.
- You must sanitize your data ($_GET['p']) before executing a query (see below). Either use mysql_real_escape_string() or make up a regular expression to weed out all non-numbers.
- It'd be neat if you modified the class to support method chaining.

For example:
PHP Code:
$page= new pagination;
$page->connect("host","username","password","dbname");
$page->setMax(25)
     ->
setData("tablename")
     ->
display()
     ->
displayLinks(5
- I do believe that for greater flexibility, that you should perhaps accept the dots ('.....') as a parameter in your constructor.
- I'm anal about standards, but you should replace <br> with <br />

You should probably have a look at the following. http://dalemooney.lost-soldiers.com/...imple.php?p=1-
http://dalemooney.lost-soldiers.com/...le.php?p='
bdm is offline  
Reply With Quote
The Following User Says Thank You to bdm For This Useful Post:
Rendair (12-10-2007)
Old 12-07-2007, 09:04 PM   #3 (permalink)
The Addict
Upcoming Programmer Top Contributor 
 
Rendair's Avatar
 
Join Date: Nov 2007
Location: UK
Posts: 319
Thanks: 18
Rendair is on a distinguished road
Default

yeah the class has its flaws of course, but hey haven't used classes in awhile. Thanks for the tips
__________________
www.jooney.co.uk - the online portfolio
Send a message via MSN to Rendair
Rendair is offline  
Reply With Quote
Old 12-07-2007, 09:06 PM   #4 (permalink)
bdm
The Acquainted
Good Samaritan 
 
Join Date: Nov 2007
Posts: 127
Thanks: 14
bdm is on a distinguished road
Default

Quote:
Originally Posted by Rendair View Post
yeah the class has its flaws of course, but hey haven't used classes in awhile. Thanks for the tips
Yeah, don't think I was trying to be harsh or anything.
bdm is offline  
Reply With Quote
Old 12-12-2007, 10:24 PM   #5 (permalink)
The Acquainted
Upcoming Programmer 
 
CMellor's Avatar
 
Join Date: Sep 2007
Location: Leeds, UK
Posts: 141
Thanks: 6
CMellor is on a distinguished road
Default

I'm gonna make my own pagination function, but base if from this code, which I hope you don't mind me doing (It's only for my personal use) but I don't use classes in my current project (I knew nothing about them really when I started my project... I learnt a thing or two while been here though :P) so am gonna try and just make it into one function.

Quick question: would this work without having the display() function? I'd be using the function to paginate data in different tables, so each output would be different, but the pagination links would be the same.

Hope you understand.
- Chris.
__________________
Not quite a n00b...
CMellor is offline  
Reply With Quote
Old 12-12-2007, 10:43 PM   #6 (permalink)
Moderateur
RegEx Guru PHP Guru Top Contributor Advanced Programmer 
 
Salathe's Avatar
 
Join Date: Apr 2007
Posts: 1,393
Thanks: 5
Salathe is on a distinguished road
Default

A fair starting point, but (please correct me if I'm wrong) a pagination class should not be dealing with the database at all. It should just be able to paginate a generic set of 'things' (be they db records, array items, class properties, etc) and be only concerned with doing the job at hand -- paginating. Nothing more!

Now imagine if you had your current class, and decided to use SQLite, XML or even web services as the data source. Would you create x number of pagination classes to fit each data type?

Along similar lines, I think it would also be a good idea to think about the output from the class. Not everyone is going to want to use tables but in your class they're hard-coded. Some other class should be able to take the results from your pagination class and deal with them in any manner -- keeping the system flexible. To sum up, I think this class is trying to do way too many things where it should really be focused on doing one thing, neither grabbing database data nor dictating how the paginated results should be displayed.

I understand that this entire post is pretty much rubbishing your class, but please understand that just because I would do something differently doesn't make it right. At the very least, I hope to have given you some food for thought on what exactly should go in any particular class.
Salathe is offline  
Reply With Quote
The Following User Says Thank You to Salathe For This Useful Post:
Rendair (12-13-2007)
Old 12-13-2007, 12:28 AM   #7 (permalink)
The Acquainted
 
Join Date: Sep 2007
Location: Arizona
Posts: 114
Thanks: 10
Andrew is on a distinguished road
Default

Salathe: How would you go about just making it just 'paginate'? Would you pass an array through the class parameters and use that array to cycle through and create the different pages?
Send a message via AIM to Andrew Send a message via MSN to Andrew
Andrew is offline  
Reply With Quote
Old 12-13-2007, 06:02 AM   #8 (permalink)
The Contributor
RegEx Guru 
 
Join Date: Dec 2007
Location: Belgium
Posts: 60
Thanks: 6
Geert is on a distinguished road
Default

Quote:
Originally Posted by Andrew View Post
How would you go about just making it just 'paginate'?
I agree with Salathe. Two important points made: make it generic and don't start outputting html in the class.

It happens that I'm the guy who developed the Pagination library for Kohana, which lives up to the above two conditions.

You set only the necessary items: current page, total items, items per page and possibly a base url. The Pagination library takes it from there. The nice thing is that with just one word you can switch from style, e.g. classic or extended or whatever template you provide in the views/pagination folder.
__________________
Kohana - PHP5 framework
Geert is offline  
Reply With Quote
Old 12-13-2007, 07:48 AM   #9 (permalink)
The Addict
Upcoming Programmer Top Contributor 
 
Rendair's Avatar
 
Join Date: Nov 2007
Location: UK
Posts: 319
Thanks: 18
Rendair is on a distinguished road
Default

Quote:
Originally Posted by Salathe View Post
A fair starting point, but (please correct me if I'm wrong) a pagination class should not be dealing with the database at all. It should just be able to paginate a generic set of 'things' (be they db records, array items, class properties, etc) and be only concerned with doing the job at hand -- paginating. Nothing more!

Now imagine if you had your current class, and decided to use SQLite, XML or even web services as the data source. Would you create x number of pagination classes to fit each data type?

Along similar lines, I think it would also be a good idea to think about the output from the class. Not everyone is going to want to use tables but in your class they're hard-coded. Some other class should be able to take the results from your pagination class and deal with them in any manner -- keeping the system flexible. To sum up, I think this class is trying to do way too many things where it should really be focused on doing one thing, neither grabbing database data nor dictating how the paginated results should be displayed.

I understand that this entire post is pretty much rubbishing your class, but please understand that just because I would do something differently doesn't make it right. At the very least, I hope to have given you some food for thought on what exactly should go in any particular class.

I agree with you it has flaws, but it was merely a way of showing some kind of back-bone. Thanks for the advice, much appreciated
__________________
www.jooney.co.uk - the online portfolio
Send a message via MSN to Rendair
Rendair is offline  
Reply With Quote
Old 12-13-2007, 09:28 AM   #10 (permalink)
Super Moderator
Advanced Programmer 
 
bluesaga's Avatar
 
Join Date: Sep 2007
Posts: 165
Thanks: 0
bluesaga is on a distinguished road
Default

If you want to see a simple pagination example that doesn't require a specific data point, check a previous post of mine: please check my code
__________________
Halo 3 Cheats
bluesaga is offline  
Reply With Quote
Old 10-18-2012, 01:12 PM   #11 (permalink)
The Addict
 
Join Date: Oct 2012
Posts: 244
Thanks: 0
dashixiong is on a distinguished road
Default

Some conservatives have Coach Factory Outlet pushed that critique further, saying that Mr. Obama’s policies are too costly, often assist the wrong people Louis Vuitton Belts and could have the paradoxical effect of driving up college costs. The dispute turns not just on different Coach Factory Outlet assessments of how policies play out, but on differing philosophical views about the role of government. During Gucci Belts his time in office, Mr. Obama has sharply increased aid to low- and middle-income students, notably through the Pell Grant Coach Factory Outlet program, which grew from $14.6 billion given to 6 million students in 2008, to nearly $40 billion for Coach Factory Outlet almost 10 million students this year. His administration also made it easier to request aid, shortening the Coach Factory Online complex federal application and allowing people to transfer their financial information electronically from the Internal Coach Outlet Online Revenue Service database. But while many education experts laud his efforts, analysts of varying political Coach Outlet Online stripes have also questioned how much impact some of the president’s policies will have, noting that the prices Coach Online Outlet charged by colleges, and student borrowing, continue to climb.But behind the headlines about soaring costs, the Coach Factory Outlet Online reality is more complex and wildly uneven, because a growing number of students receive Coach Outlet Online financial aid, and only relatively high-income families pay those fast-rising sticker prices. Adjusted for Coach Factory Online inflation, the College Board calculates, the average net price changed little over the last decade at private Coach Factory Outlet schools, and rose only modestly at public ones.Defending federal spending, Arne Duncan, the secretary of Hermes Belts education, said that for more than 30 years, college prices had risen even when federal aid had not, leading him to believe Coach Factory Online there was zero correlation.
dashixiong is offline  
Reply With Quote
Old 10-22-2012, 09:24 AM   #12 (permalink)
The Addict
 
Join Date: Oct 2012
Posts: 244
Thanks: 0
dashixiong is on a distinguished road
Default Coach Outlet

You’ve relativelyCoach Outlet recently arrived in New Delhi after living in two of Asia’s other great cities,Coach Outlet Store Online Tokyo and Hong Kong, for several years. Do these cities feel like they’re part of the same continent? Yes, and no. In terms Coach Factory Onlineof infrastructure, they couldn’t be more different. Getting regularCoach Outlet power and water at my house in New Delhi is never a sure thing, even though Coach Purse Outlet OnlineI’m paying the same rent that I paid in Tokyo and almost the same electricity prices. Both Hong Kong and Tokyo are also crowded places,Coach Factory Outlet Online but both cities are incredibly well planned and efficiently run. Efficient is not a word I would use to describe my Coach Bags Outlet Onlineday-to-day life in New Delhi. On the other hand, one thing that I think Hong Kong and New Delhi have in common isCoach Handbags Outlet a shared sense of optimism — a feeling that the best is yet to come. That’s definitely not the feeling you get in Tokyo,Coach Outlet Online or in the U.S. when I go home. It’s a big part of what I find addictive about living and working in this part of the world. You feel like you’re watching the future unfold.
dashixiong is offline  
Reply With Quote
Old 01-29-2013, 12:53 PM   #13 (permalink)
The Addict
 
Join Date: Oct 2012
Posts: 244
Thanks: 0
dashixiong is on a distinguished road
Default

Organizers said Coach Outlet Online was opportune because the battle’s 150-year anniversary is in December, and Fredericksburg Coach Factory Outlet has been preparing to mark the sesquicentennial. in the new agreement is that Coach Outlet Online revolutionary councils from 14 Syrian provinces now each have a representative, though not all live Coach Online Outlet in Syria. The hope is that will bind the coalition to those inside the country. Perhaps Coach Bags Outlet the most important body the new group is expected to form is a Revolutionary Military Council Coach Factory Online to oversee the splintered fighting organizations and to funnel both lethal and nonlethal Coach Factory Outlet military aid to the rebels. It should unite units of the Free Syrian Army, various militias Coach Outlet Store Online and brigades in each city and large groups of defectors. Before the ink was even dry on the Coach Outlet Store final draft, negotiators hoped that it would bring them the antiaircraft missiles they crave to Coach Factory Stores take on the Syrian Air Force. The United States and Britain have offered only Coach Handbags Outlet nonmilitary aid to the uprising. A similar attempt by the Syrian National Council to Coach Factory Store supervise the military never jelled. Organizers said funding was too haphazard. Eventually foreign Coach Factory Online governments like Qatar and Saudi Arabia, which are financing and arming the rebels, found Coach Factory Online their own favorite factions to deal with. Foreign leaders notably including Secretary of State Coach Outlet Hillary Rodham Clinton urged this unification largely so they could coordinate their Coach Factory Outlet efforts and aid through a group of technocrats. Once it receives international recognition, the Coach Outlet Store Online coalition is supposed to establish a temporary Coach Outlet Online military never jelled.
dashixiong is offline  
Reply With Quote
Old 02-01-2013, 11:08 AM   #14 (permalink)
The Contributor
 
Join Date: Feb 2013
Posts: 32
Thanks: 0
sara111 is on a distinguished road
Default

Employees can expect a dynamic, supportive and openly communicative environment accommodating new levels of innovation, technology and forward-thinking solutions.
recruitment at candor
full time jobs
job agencies
travel agent jobs
recruitment firms
sara111 is offline  
Reply With Quote
Reply


LinkBacks (?)
LinkBack to this Thread: http://www.talkphp.com/advanced-php-programming/1660-advance-pagination-class.html
Posted By For Type Date
PHP Object Orientated: Creating an Advanced Pagination Class Tutorial This thread Refback 01-10-2008 01:21 PM
PHP OOP Object Orientated: Creating an Advanced Pagination Class Tutorial This thread Refback 01-10-2008 01:09 PM
Advance Pagination Class - TalkPHP This thread Refback 12-29-2007 10:41 PM

Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On


All times are GMT. The time now is 06:09 AM.

 
     

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.1.0
Inactive Reminders By Icora Web Design