Tutorials

PHP Basic Pagination

by Crayon Violent on Jun 18, 2008 6:11:55 PM

Okay before anything else, here is the code in all it's full and basking glory, because there's nothing more I hate about tutorials than how people like to break them all into itty bitty little chunks and you have to copy and paste, copy and paste, copy and paste. It's aggravating....and yet it's somewhat contrary to the theme of this tutorial. Isn't it ironic?

Okay so there's the code. Basically the idea is to:

- Find out how many rows you have in your table
- Find out how many pages you want to make, based on how many rows per page you want to show
- Find out what page we're on
- Pull out just the rows of the current page
- Display the info
- Make some links to go to the first page, previous page, some pages around the current page, the next page, and the last page.

There's comments aplenty in the code, so you may be able to figure out what's going on based on that, but let's go ahead and break it down for some further commentary. Moving on...

Comments

Thank god for that. I'm tired of having to tell people to google for pagination tutorials rather than being able to point them to something specific!

Reads well CV.

1. Ben Smithers on Jun 19, 2008 8:47:14 AM

You said there's nothing more annoying then having to copy and paste, copy and paste, copy and paste. But the point is you're not learning anything when you do it that way so they make it hard to just cheat and not learn.

2. Rezert on Jun 20, 2008 8:48:44 AM

If someone is looking to cheat, they would just disregard the commentary and copy and paste it anyways. I'm not in the business of "forcing" people to learn. I'm in the business of giving people the material to learn, the best way I know how.

If someone feels they need to be walked through each piece of code, it's there for them. If someone feels they can learn it by just looking at the code, it's there for them. If someone feels they can just c/p it into their code and hope some magic wand is waved...again, that's their prerogative.

It is certainly my choice to make tutorials, but if I do endeavor to do so, it is no longer a choice, but a responsibility to make the resource as available as possible. It is at no point in time my place to police how people use that information. In fact, I refuse to accept responsibility for that, at all. How do I know that someone will not use it for malicious purposes? Should I be held responsible for that? I think not!

3. Crayon Violent on Jun 20, 2008 10:35:51 AM

I love the commentary on the tutorials. If I get stuck I always refer back to it. That being said I like the idea of having all the code up front so I can tinker and screw it up on my own. It's how I learn best.

Thanks for the great tutorial btw.

4. Rodney Moore on Jun 20, 2008 3:45:30 PM

Point well stated.

5. Rezert on Jun 20, 2008 7:38:02 PM

I cannot get this code to work. Has anyone encountered the same problem?

6. norwid on Jun 22, 2008 1:50:14 PM

can you be more specific?

7. Crayon Violent on Jun 22, 2008 4:48:14 PM

Thank you CV great code

8. Christopher Burnside on Jun 24, 2008 7:07:35 AM

Thank you Crayon Violent for the most excellent tutorial...
Very simple to follow, the only real changes that I had to make were, instead of using "{$_SERVER['PHP_SELF']}?", using "{$_SERVER['REQUEST_URI']}&" so it would tack on the pagination to my already existing stream of $_GET variables...

9. webent on Jul 3, 2008 4:08:16 PM

SQL_CALC_FOUND_ROWS can be used under MySQL instead of querying the first SELECT COUNT(*) FROM NUMBERS

10. petitchevalroux on Aug 1, 2008 8:02:26 AM

thank you so much!! just what i needed... been searching the web for 3 hrs... i really appreciate it. now i can finally finish my project... thanks a bunch CV!!!!

11. vherhonne on Aug 2, 2008 12:40:41 PM

This tutorial was great in helping solidify my pagination technique! Easily explained for dummies as well, always helps.

12. GreenUser on Aug 15, 2008 3:19:29 PM

I think the lines that find out the current page are both more readable and better written as:

$currentpage = is_numeric($_GET['currentpage']) ? (int) $_GET['currentpage'] : 1;

At minimum, isn't it redundant to check both isset() and is_numeric()?

13. tmallen on Sep 1, 2008 8:50:48 PM

Thank you very much for this script, Crayon!

I must say, however, that I do have a small problem with it . . .

The problem is, the pagination links appear on the page whether results are returned or not. In other words, if someone conducts a query on my site which returns no results, the links to pages 1, 2 and 3, along with ">" and ">>", will appear nonetheless, thus:

1 2 3 > >>

And when clicked, these links will go to blank pages.

How can I fix this? I don't want links to blank pages if no results are returned.

I thank you for your advice.

14. Fluoresce on Sep 16, 2008 3:36:32 PM

Just wrap a condition around the whole pagination section.

if ($result > 0) {
// pagination section here
}

15. Crayon Violent on Sep 17, 2008 5:34:48 PM

i have a problem ,when i send with post method a query to my pagination page
the firt time i see the page ok but when i click on second page link i don't see nothing...

the pagination work if i write the sql query into my pagination page but not work if i send whit post method the sql query

i think that is the PHP_SELF that when reload page cancel the data into variable.

code :

$data1 = mysql_real_escape_string(@$_POST['data1']); //data scatto
$data2 = mysql_real_escape_string(@$_POST['data2']); //data scatto

$dida = mysql_real_escape_string(@$_POST['dida']);
$dida1 = mysql_real_escape_string(@$_POST['dida1']);
$nome = mysql_real_escape_string(@$_POST['nome']);
$stagione = mysql_real_escape_string(@$_POST['stagione']);
$tutto = mysql_real_escape_string(@$_POST['tutto']);

if ( $data1 == "" && $data2 == "" && $dida == "" && $dida1 == "" && ($nome != ""))
{

$sql = "SELECT id,nome,path_basse,path_alte,path_medie,descr_usata,larghezzab,altezzab,categoria,didascalia,date_format(data_evento,'%d-%m-%Y')as datetrans,note FROM foto where nome like '%$nome1%' order by data_evento asc LIMIT $offset, $rowsperpage";


}
any idea ?

thanks Biciodark

16. biciodark on Oct 14, 2008 8:20:25 PM

I have exactly the same problem. First page comes ok. but other pages are empty. If you find an answer please let me know.

17. hakmir on Oct 16, 2008 5:52:14 PM

The problem is that your posted vars do not carry over from page to page. They are only passed to the page from the initial form submission. To keep them persisting, you need to either make them session variables or else add them to the links to be passed through the url and retrieved via the GET method (like the other vars).

If you are using a lot of posted info I would suggest using sessions, as there is a limit on how long a url string can be. Also, sessions are more secure.

18. Crayon Violent on Oct 16, 2008 6:28:17 PM

Hi CV, cool script.

I don't know if anyone noticed this but in line 65 of the script it says:

for ($x = (($currentpage - $range) - 1); $x < (($currentpage + $range) + 1); $x++)

Now, if the page range is 3 the above line will actually create 4 page ranges instead of 3 left of the current page.

If one change the above line to read:

for ($x = ($currentpage - $range); $x < (($currentpage + $range) + 1); $x++)

it will correctly display the page ranges left of the current page.

Am I correct?

Kayosz

19. Kayosz on Oct 27, 2008 10:19:05 AM

Ah, you are right. Don't know why I did that. Perhaps I was thinking ahead to +1 or something, I dunno, lol. Changed the tut code. Thanks for pointing that out :)

20. Crayon Violent on Oct 27, 2008 11:02:34 AM

Hi Crayon, nice tut. =D

I'm trying to put a delete query in the pagination. It works....
but it doesn't refresh properly. Once i hit DELETE, it's highlighted purple as purple, but doesn't go away till i refresh the page.

while ($list = mysql_fetch_assoc($result)) {
// echo data
echo $list['id'] . " : " . $list['number'] . <a href='{$_SERVER['PHP_SELF']}?currentpage=$currentpage&amp;var=$list[id]'>DELETE</a>" . "<br />";
} // end while

$a=$_GET['var'];

if(isset($a)){
$sql1="DELETE FROM numbers WHERE id='$a';";
$query1=mysql_query($sql1, $conn);
}

Is there anyway around this? thanks~

Thanks,

Daniel (new to php)

21. yepwingtim on Oct 31, 2008 7:35:49 PM

if you guys want to quickly go to a specific page... =)

echo "<form name='page' id='page' action='{$_SERVER['PHP_SELF']}?currentpage={$_GET['currentpage']}' method='get'>";
echo "<input type='submit' value='Submit' /> <br>";
echo "<input type='text' name='currentpage' id='currentpage' /> <br>";
echo "</form>";

22. yepwingtim on Nov 1, 2008 3:15:23 AM

Daniel,

Simply move the part of your code deletes stuff to before the part that displays stuff, and you should be good to go. Although I have to tell you that what you are doing with that delete code block is not safe. All you are doing is checking to see if the var is set and then using it in your query, without making sure that it holds what it's supposed to be holding. Read up on sql injection to see what I mean.

23. Crayon Violent on Nov 2, 2008 1:37:43 AM

Great Job!

I never know it was that easy.
You made it easy!

Thank You!

24. mahender on Nov 25, 2008 2:30:14 AM

Hi,
I have found this tutorial very useful and easy to understand. However, I would like to apply the same code to a php mysql photo gallery. It works fine with this, but I only want the output section to do 4 thumbnails per row (as in after it echo's out 4 pictures there needs to be a <br /> at the end) and then start the next row. So I think I have to change the while() statement to a for loop. If I could have any help in modifying this, it would be greatly appreciated.

25. sw45acp on Dec 17, 2008 7:47:27 PM

before the while loop, do something like this:

$x = 1;

and inside the while loop, do something like this:

echo ($x % 4 == 0)? "<br/>" : "";
$x++;

26. Crayon Violent on Dec 17, 2008 9:02:09 PM

Yes, it does work, only when I added $x++ after the new statement, inside the while loop. Thank you for your help. What does the ? and the : mean in this syntax?

27. sw45acp on Dec 17, 2008 9:12:24 PM

It's a ternary operator.

(condition)? do this if true : do this if false;

Shorthand for an if..else statement. Same as writing this:

28. Crayon Violent on Dec 17, 2008 10:04:13 PM

ok thank you so much (you really know your stuff)

29. sw45acp on Dec 17, 2008 10:15:02 PM

I was wondering if anyone else has hit the 60 rows max issue I'm having
It doesn't seem to want to go past that (goes to page 4)

30. bateman on Dec 22, 2008 11:22:12 AM

Great script.

I would like to display the results in a table format rather than a colon delimited list.
I've tried to modify this echo statement:

echo $list['regnum'] . " : " . $list['name'] . " : " . $list['color'] . "<br />";

With one to echo out <tr><td> of the 3 fields I have with no luck.

Help would be greatly appreciated.

31. OHMichelle on Dec 28, 2008 4:54:07 PM

Hey OHMichelle,

Showing your data in tabular format is pretty easy. I'm assuming that you want each row of data in its own table row (tr), and each of those variables in its own column (td). The code will look something like this:

32. Crayon Violent on Dec 28, 2008 5:56:55 PM

The code is great, i'd prefer something smaller but after testing i couldnt really find a way to do that, but the big thing you helped me with was the ternary operator, i've seen it all over the place never known what it was and its a nightmare to google about. Its made me curious if you can have an elseif ternary statement. e.g.
$cheese = ($hello == "1") ? "1" : ($hello == "2") ? "2" : "3";
If you do answer my question i'd rather you pm me it, cause ill forget to check this tutorial.
Thanks alot CV

33. Flames on Dec 30, 2008 3:55:27 PM

You can nest a ternary inside another ternary but it's not the same as if..elseif...else. It's more like this (2 nested ternaries, 1 inside true, 1 inside false)::

Just google 'ternary operator' I'm sure you can find much better examples of what it can and can't do. In-depth look at conditions isn't really the scope of this tutorial...

34. Crayon Violent on Dec 30, 2008 7:52:50 PM

First of all, thanks for the tutorial. Just what I was looking for. It's simple, straight-forward, and well explained. (I'm going to recommend it on my blog.)

Also, when implementing it on a project I'm working on, I changed:
$r = mysql_fetch_row($results);
$numrows = $r[0];
/*To:*/
$numrows = mysql_num_rows($results);

Any thoughts? (Performance wise, etc.) It seemed to work just as well. It actually didn't work quite right the first way, and I'm thinking that's because my table started with a high index because I had been testing. I tried this and it worked. Anyway...

Thanks again!

35. katendarcy on Jan 19, 2009 11:24:58 AM

I am so close to get this working but its not for some reason, I had it working with the basic queries but once i try and add in my php code it all falls over.

I can do the pages manualy but the links at the bottom are missing it is for a xml output file so its kind of tricky to get the links working as its a rss feed.

Great bit of code thank you for the trouble of writing it.

Will ask on the forum for a bit of help see if anyone will be kind enough to help me.

36. lordshoa on Jan 28, 2009 6:17:48 AM

Could you go over how to add links and images to something like this?

echo "<table>";
while ($list = mysql_fetch_assoc($result)) {
echo "<tr>";
echo "<td>" . $list['regnum'] . "</td>";
echo "<td>" . $list['name'] . "</td>";
echo "<td>" . $list['color'] . "</td>";
echo "</tr>";
} // end while
echo "</table>";

37. bluewaves on Mar 28, 2009 5:14:23 PM

The while loop is where each row from the returned query is pulled. You can format the results any way you like. The table I have is just an example. You can use echo to echo out whatever you want. Or print. Or close the php tag out ?> and just write out what you want and open it back up <?php when it gets back to the code.

As far as what you actually output...you can wrap stuff in html tags and your browser will mark it up just like it normally does. So for instance, if I wanted to make all of the data a certain color, I could just do this:

Or I could add an id or class attribute to something and mark it up with css. How you want to format it isn't really a php issue...

38. Crayon Violent on Mar 28, 2009 6:02:43 PM

Thanks for spending the time to do this, you're officially a legend.

Rob.

39. robm2002 on Apr 3, 2009 5:50:52 AM

The column ‘number’ will contain urls. I would like all the data from ‘number’ to have links. Can you help me with this?

No need to reply, I worked it out. Thank you for writing this script, it works great!

40. bytesize on Apr 12, 2009 8:06:22 PM

head of u..............................
nice sir .......
can u explain curl and cron job also for me sir.............................

41. man12_patil3 on May 14, 2009 7:21:37 AM

Crayon Violet, this tutorial rocks. I am definitely not the brightest bulb in the box and even I could understand it (everyone's comments and your answers to them helped also). Excellent stuff!

42. JPark on Jun 13, 2009 10:52:02 PM
Login or register to post a comment.