July 7, 2006 at 4:09 pm by
jason
Some people were interested in seeing the code I used to create the pagination for WineLog, which was based on the style of pagination used on sites like Digg and Flickr. I’ve put together a little demo which should help out anyone who is trying to create the same effect on their site.

(digg-style pagination demo)
[...] I hope this helps those who were interested. Please post any questions or comments concerning the code at the Stranger Studios blog post on the demo. Thanks. [...]
Any simple way to integrate this into WordPress? I’ve been trying but have run into a lot of error messages.
Hrmmm, this saves a hell out of my time. I’m planning to write similar like this. Thanks Jason!
Jason
(yes, i’m jason too)
[...] Paginate your site like-digg [...]
Nice, this is useful! I’ve ported a version to Perl, which I’ll email to you.
[...] Earlier in the year, I wrote a tutorial on how to create pagination similar to Digg’s. The article focused on the basic algorithm for displaying the pagination, and there was definitely some opportunity for improvement in its implementation. [...]
Great code!!!
I was tring to use it in my site, but the ” page nav buttons ” did not show up.
The listed iterms are fine. any hint?
BTW seems not work when I check the page source.
Thanks
Hi!
I have problem vith this script “undefined variable $page”!
So i add >>>if (isset($_GET['page'])){$page=$_GET['page'];}else{$page=0;}0)
$start = ($page – 1) * $limit;
……..
Regards
[...] La creación de esta plugin de paginación fue basada en la versión modular creada a partir de la original creada por strangerstudios.com. [...]
[...] This is ASP based pagination script, similiar to Digg.com pagination. The credit goes to Jason Coleman who written this script in PHP and I simply converted this into ASP. I have attached screenshot this will help you to see how it looks like. [...]
[...] I’ve been on a bit of a digg kick lately and I like how they handle paging so I decided to create a GridView control that uses custom paging similar to digg’s. The algorithm is based on this post. As far as html output goes, this should be fairly close to the actual output on digg and I’m using digg’s stylesheet in the demo. [...]
Hey, great script!
One note for people working with php and not being an expert, I had a small issue come up where it thought the numbers were part of the variable. I had to change the code slightly…
FROM:
$pagination .= “1“;
$pagination .= “2“;
TO:
$pagination .= “1“;
$pagination .= “2“;
Brad, they look the same to me. Can you explain the change?
If I had more time I would take a look at the code to see what you were talking about.
Cool stuff!
Got any Javascript version of this?
Thanks so much to you digg, you are a sweet man. I am trying to use your pagination system on my website.It look so nice, that i am going to change all what i had.
One more again thanks…You can just see the system here http://www.icom7.com
Some people are finding out that you may have to declare the variables passed in through the URL at the top of your code. (my server settings allow me to just access them directly)
You can add some code like the following to the top:
$page = $_REQUEST['page'];
Rinse and repeat for any other variables you’re passing around.
Hi Jason,
I have not taken this live on my site yet, I am just testing at this
point…..
But, I have a question… I have a var, search, in a form that calls this page. The script seems to execute fine, but it is completely empty even when I make a selection that should yield ~150 results.
Any ideas on what I could be doing wrong?
Thanks,
Jim
Hi, Jim. I’d need to see more of your code to help you out. My guess is there is some error in your SQL query. Make sure that the variable passed by your form really has something in it. Do an “echo $search” at the top of the script. If you aren’t seeing what you should, make sure you are setting the variable (needed on some servers) like so “$search = $_REQUEST['search'];”.
Good luck. Feel free to email me for more help.
Hello again Jason,
The vars are being passed properly. I placed a print statement in the script to verify this.
My question is what var should have the search term in it?
I tried search to no avail….
Could someone please send me a reference of a simple page that impliments this script with just a few pictures on it. I’m really new to this stuff and can not figure it out. I want to use it on my site – imediadotcom.com
sorry, i also don’t use sql.
The digg style solution here is great. Do you know how to incorporate this into Movable Type 4? I see that you have a WordPress solution. It’d be great if this could also work in MT4. Thanks.
I’m not as familiar with Movable Type and its plugins. You can hit up Mis-Algoritmos here:
http://www.mis-algoritmos.com/2007/05/27/digg-style-pagination-class/
btw, that’s an interesting class implementation. It’s pretty sweet. I know though that when I was first learning PHP, classes were almost always over kill for me and confused me a bit. If this is you, take a look at some of the older code.
However, if you are already familiar with classes and/or a PHP expert already who is looking to save time, take a look at that class and use it.
I am having troubles implementing the digg style pagination system into my project. http://www.superwebcamgirls.com can anyone help me with a simple more detailed code.
The only thing I had to add at the beginning was:
if(isset($_REQUEST["page"])) {
$page = $_REQUEST["page"];
} else if(isset($_POST["page"])) {
$page = $_POST["page"];
} else if(isset($_GET["page"])) {
$page = $_GET["page"];
}
after I made the connection to the DB.
You can see it at work:
http://www.axewar.com/topaxe.php5
Thanks for this excellent piece of script!! Easy to implement and works like a charm!
Mahesh,
Looks great on your site. Very nice site also, btw. I should probably add your code to the top of my implementation. It’s only needed if you don’t use the register_globals. However, if you do register globals, this code doesn’t hurt.
Sander, glad it worked out for you.
how to integrate like this :
Displaying 1 – 16 of 365 queries [Total 22 Pages]
thanks,
Kanchan
How to show in this pagination??
Showing from 1 to 20 from 200 queries.
I really want to use this script but not really understanding how you implement the code into the site. I’m a php newbie- please help!
In the modularized version of the function, diggstyle_function.txt, there is a typo on line 55. ($adjacents * 3) should be ($adjacents * 2).
“In the modularized version of the function, diggstyle_function.txt, there is a typo on line 55. ($adjacents * 3) should be ($adjacents * 2).”
Thanks for the fix, this needs to be implemented in the code given otherwise the “next” button gets disabled when you get to the last page (not the 2 lasts, the last before it), unless your $adjacents is set to 1.
Is anyone still offering help with this? I would really like to use this with my Zenphoto gallery. Please help!
Kanchan, if you are still interested email me (use contact form). I’ve done this on some of my projects and can try to get an example on this site.
Jason
Thank you very much. tried it and loved it. working perfect
Ubercool script, I made it work with jQuery at http://www.dealspost.com (scroll to the bottom). Only one glitch I have found: if you have a lot of records in the database (hundreds) and you set adjacents = 3 then on page 9 will dissappear link Next and pagination will not generate links to pages 10+ except for the last two pages. But if you change to adjacents=2 it works like a charm.
Thanks a lot for your work.
Joe
Script works perfect if I want to select everything from the table. But When I chose certain categories from the table, first page comes ok. but other pages are empty.
I used this query
$query = “SELECT * FROM $tablename WHERE country=’$country’ AND typeoffood=’$typeoffood’”;
Another thing is, the number of pages that is showing is for whole table because of this code I think:
$queryCount = ‘SELECT count(*) FROM ‘.$tablename;
I am very new to php. Can you help?
Am trying to use the pagination code but its not giving me any results. What am i missing. Nothing completly shows up. Please help me
firstly,this is good coding..
but i have some problem.the page is always shows this error :
Use of undefined constant num – assumed ‘num’
this is my coding:
$query = “SELECT COUNT(*) AS num FROM $tbl_name”;
$total_pages = mysql_fetch_array(mysql_query($query));
$total_pages = $total_pages[num];
did i do anything wrong??please help me..actually,i’m not very good in php..please help me..i need help coz this part is important to me..i need this ASAP..
Thanks..
excuse the trite question, but where I take the code in my db?
What exactly should I enter in this part of the code? “Place code to connect to your DB here.”
First, folks with DB or other app issues, I’m sorry I can’t help you more. If you have the budget, you can contact us (use link in top menu), and we can take a look at your code at our consulting prices.
Secondly, someone emailed me with some minor updates to the code and CSS that offer better scaling/resize support for IE browsers. The code on the demo site has been updated.
Thanks!
thanks to this code .
this is good coding.. I m implementing this code to my all sites that i had done..
Thanks a lot….
Wonderful pagination script , I used it already, thanks a lot.
Sir,
i impliment paging using your code.but now i am able to see links of all pages. but when i am clicking the corresponding page, i cant able to access the result.
only i got the result when the value of page=0. i think value of page is not coming properly.same thing i am using
$page = $_GET['page'];
please help me
You guys are great! thanks for this little tool. It really ease the work load
Thanks for beautiful work.. Im use it in administration panel paginations..
I am newbie to PHP but I managed to display correctly the first page of the collection of my records . The navigation bar doesn’t show. I greatly appriciate if any would suggest some ideas !
Sweet !!! Thanks
Just noticed one error
//close to beginning; only hide later pages
if($page < 1 + ($adjacents * 3)) {
should be change to
//close to beginning; only hide later pages
if($page < 1 + ($adjacents * 2)) {
So i’ve implemented your script on my site and it works great. i just have two quick things. Its adding two extra pages that I don’t need. So instead of just listing pages 1-3 it lists 1-5 but with pages 4 & 5 being blank. Any ideas on how to get rid of those extra pages.
Also I was wondering if it could keep track of and send two variable at once. You’ll see on the site link that I have entries being pulled from one database but organized into two categories. I’ve named the page variable just $page and $page1. Could I keep track of both at all the time so that the user could choose page 3 on General news and then page 2 on Community news after the page refreshes and have it keep track of where it is for both.
Thanks again for the script really a huge time saver for me.
Good morning: I have this code working perfect. I am trying to add to the CSS to make the text to the right of the image and I’m not able. Does anyone have any suggestions? Thanks
thanks for this info..
nice tips..
Hi
i have a problem my pages start at zero and i want them to show as page one and the link to still show the zero
so it would look like this
1 2 3 4 <—- the link for number one should be page=0 and link for number 2 should be page=1 ect
any idea how i can do that
nice info..
good for me and all
Thats great! But I can´t use “page” as an element, because it´s already taken by my cms. Is it possible to change that?
I changed “page” already 3 times to “site”:
if ( (int)$_GET['site'] > 1 ) $page = (int)$_GET['site'];
$pagestring = “?site=”)
and it begins to work, but I think I missed something. Any hints?
Script looks great and had it installed on my page in about 10 minutes. It displays the correct number of items ( as per limit) on the first page just fine and calculates the proper number of pages to use in pagination menu bar. The pagination menu bar looks great. Problem is… I only get results on the first page. All of the other pages come up with blank results. In my test, there are 7 items to display, have the limit set to 3, pagination menu shows there are 3 pages of results and the pagination button links show the correct link address. But, if I click on button [2] (or other) it delivers blank results I’m reasonably fair with php and have spent a number of hours trying to get it to work right and unfortunately it’s just not happening. Any advice would be greatly appreciated. (website address is link to test page.)
@Randal, make sure you get the $page var by adding $page = $_REQUEST['page']; to the top of your script.
I really need to update the script/demo.
If that doesn’t work, try echoing the SQL query being made and running that through phpMyAdmin or something to see if there are errors. I’m guessing the SQL query is not being put together correctly.
Hello
I google and found this code for pagination and it´s great works very nice execpt for a litle matter.
I face the same problem as Randal.
I´m using this sql-query:
$sql = “SELECT bildnr, fotograferingsplats FROM $tbl_name WHERE fotograferingsplats = ‘$fotoplats’ ORDER by bildnr desc LIMIT $start, $limit”;
When i use the variable $fotoplats the second page gets blank
If I manuelly code the variable to “kusmark” then the script works perfectly.
Can you please help me?
All the best from Sweden
Erland Segerstedt
Is $fotoplats being set properly. Echo out $sql and check that the query is created properly. You can cut and paste that into phpMyAdmin or something similar to see a MySQL error you may be getting.
I am guessing you need to set $fotoplats by doing something like $fotoplats = $_REQUEST['fotoplats'], but can’t tell much from the code you submitted.
I hope this helps.
Good evening!
This is what´s going on;
First loop= variabel “$page” is nothing, “$fotoplats” has an value and “$total-pages” has an value.
Next loop = variable “$page” has value 2, “$fotoplats” is empty and “total-pages” has value 0.
Is this makeing any sence for you?
All the best from Sweden
Erland Segerstedt
The $_REQUEST didn´t work!
Erland
Hello
With this code it´s working
if (isset($_POST['sokstrang']))
{
$_SESSION['fotoplats'] = $_POST['sokstrang'];
}
All the best to you
this pagination code is very good
Thank you very much for your code
Erland Segerstedt, Sweden
Hi,
I think there is a ‘bug’ in your script.
Indeed, I replace if ($page < $counter – 1) by if ($page < $lastpage) to enable the next button if the $counter + 1 is hidden ("…")
Anyway, it's a usefull script, thanks a lot
PS : I’m talking about http://www.strangerstudios.com/sandbox/pagination/diggstyle_function.txt
Great script. Installed very quickly. Just wondering how to use the script alongside buildIUrl…for example where you script says ‘$pagination.= “next »“;’ for example. I would need a feature that would allow for something like echo ‘‘ . $i . ‘‘;
Rewrote for our use, but should be useful to others. Let me know if you notice a bug. Tx…
Just call the function passing your specific values, returns object with items for display on page, as well as the pagination code to place on your page.
[PHP]
function getPaginationItems($tbl_name, $orderby = ”, $adjacents, $limit, $targetpage) {
$items = array();
$dbh = db_connect();
$query = ‘SELECT COUNT(*) as num FROM ‘ . $tbl_name;
$result = $dbh->query($query);
if (PEAR::isError($result)) { die($result->getMessage() ); } // catch db error
$total_rows = $result->fetchRow()->num;
/* Setup vars for query. */
$page = isset($_GET['page']) ? $_GET['page'] : 0;
if($page)
$start = ($page – 1) * $limit; //first item to display on this page
else
$start = 0; //if no page var is given, set start to 0
/* Get data. */
$query = ‘SELECT * FROM ‘ . $tbl_name . ‘ ‘ . $dbh->quote($orderby, ‘text’, false) . ‘ LIMIT ‘ . $start . ‘,’ . $limit;
$result = $dbh->query($query);
if (PEAR::isError($result)) { die($result->getMessage() ); } // catch db error
while ( $r = $result->fetchRow() ) { array_push($items, $r); }
$pageItem->items = $items;
/* Setup page vars for display. */
if ($page == 0) $page = 1; //if no page var is given, default to 1.
$prev = $page – 1; //previous page is page – 1
$next = $page + 1; //next page is page + 1
$lastpage = ceil($total_rows/$limit); //lastpage is = total pages / items per page, rounded up.
$lpm1 = $lastpage – 1; //last page minus 1
/*
Now we apply our rules and draw the pagination object.
We’re actually saving the code to a variable in case we want to draw it more than once.
*/
$pagination = ”;
if($lastpage > 1) {
$pagination .= ”;
//previous button
if ($page > 1)
$pagination.= ‘« previous‘;
else
$pagination.= ‘« previous’;
//pages
if ($lastpage < 7 + ($adjacents * 2)) //not enough pages to bother breaking it up
{
for ($counter = 1; $counter <= $lastpage; $counter++)
{
if ($counter == $page)
$pagination.= '’.$counter.”;
else
$pagination.= ‘‘.$counter.’‘;
}
}
elseif($lastpage > 5 + ($adjacents * 2)) //enough pages to hide some
{
//close to beginning; only hide later pages
if($page < 1 + ($adjacents * 2))
{
for ($counter = 1; $counter < 4 + ($adjacents * 2); $counter++)
{
if ($counter == $page)
$pagination.= '$counter’;
else
$pagination.= ‘‘.$counter.’‘;
}
$pagination.= “…”;
$pagination.= ‘‘.$lpm1.’‘;
$pagination.= ‘‘.$lastpage.’‘;
}
//in middle; hide some front and some back
elseif($lastpage – ($adjacents * 2) > $page && $page > ($adjacents * 2))
{
$pagination.= ‘1‘;
$pagination.= ‘2‘;
$pagination.= “…”;
for ($counter = $page – $adjacents; $counter <= $page + $adjacents; $counter++)
{
if ($counter == $page)
$pagination.= '’.$counter.”;
else
$pagination.= ‘‘.$counter.’‘;
}
$pagination.= “…”;
$pagination.= ‘‘.$lpm1.’‘;
$pagination.= ‘‘.$lastpage.’‘;
}
//close to end; only hide early pages
else
{
$pagination.= ‘1‘;
$pagination.= ‘2‘;
$pagination.= “…”;
for ($counter = $lastpage – (2 + ($adjacents * 2)); $counter <= $lastpage; $counter++)
{
if ($counter == $page)
$pagination.= '’.$counter.”;
else
$pagination.= ‘‘.$counter.’‘;
}
}
}
//next button
if ($page < $counter – 1)
$pagination.= 'next »‘;
else
$pagination.= ‘next »’;
$pagination.= ”;
}
$pageItem->pagination = $pagination;
return $pageItem;
}
[/PHP]
$page is not defined when I copy/paste the code..
Right. I should update the code. On most modern systems. You’ll need to add to the top of the script:
$page = $_REQUEST['page'];
Hi, please I want to find out if this pagination script has to be inside my display script. This is what I mean, I already have a script that displays my records (say it is news.php) and it has worked fine all along). Now If I want to integrate your pagination script, do I paste all your codes in my existing news.php? Could your script be just included somewhere (at the top or at the bottom of my display script), which is what I tried to do but I could not get it working.
Put the pagination function in another file you are including (functions.php, lib.php, etc) and then use the function to generate the pagination.
Hi, I noticed a little bug, it you have an odd adjacent value the script doesn’t work properly. Example, if total is 5000, number per page value is 5, and adjacent value is 3, the script doesn’t work for page 9. Just fyi if someone is seeing the same problem, use an even number for the adjacent value. Thanks, and thanks for a great function!
Thanks for the comment. I may take a look and figure out what is going on. If anyone has a script update to fix this, let me know.
i added the
$page = $_REQUEST['page'];
but i have problem with this too
where is the page come?
what is this?
Sounds like something else going on in your code. I sent you an email.
BTW, the $page = $_REQUEST['page']; gets the page number that is pased via the URL in the pagination links.
Hi, your code’s really useful for what I’m doing but the next and previous buttons aren’t showing after I put the whole code inside a php file and included it in pagination.php along with “” at the bottom. The loop limit works though.
Is it necessary to have the whole code in a single file?
Thank you for your time and effort, really appreciate it!
Are you using the function? That’s the way to go. The other code is mostly so you can figure out how it works. The function should work as long as you are passing all of the parameters.
only the results apperas the css dont
Are you including the css file properly in the head section of your site?
Hello!!!
First i want to say that your tutorial is perfect!But it is the first time i use pagination and i have some problems…is there any example which has all the source code???from the start to the end..all the body!!
Thank you very much
The code should be complete. It will break though if you don’t have a database setup like that. You will need to tweak the code in the DB setup portion to get it to work on your server. I can’t give you a DB easily to test against.
Works great, that is, until I try to sort. My data is displayed in a table and each column header has an a tag that calls for a sort order by that column heading. First page sorts, but after that everything reverts to the default sort order. I thought that using the GET method was the culprit, but trials with POST yields the same result. Any ideas? Do you need more info? Thanks.
Nevermind. Figured it out. It was POST, but by concatenating the sort order variable to the page variable in the url it works fine.
correction: it was GET. The sort order variable was overwriting the pagination variable.