One of the first problems many web developers faces is that of pagination. A database query can sometimes results in hundreds, maybe thousands, of results, and they must all be displayed. Without pagination, those results create a huge, unusable mess for any user.
The problem with any automated pagination script is the preservation of variables. There is no point displaying 10 search results on each page of a result set if a site cannot remember what you searched for from one page to the next. This can one very repetitive part of programming web pages - the preservation of variables.
The following script will work around that problems. There is one downside - you must use querystring variables, rather than form variables (set a form to "GET" rather than "POST"), as otherwise the script will not retain the variables from one page to the next.
Other than that, it is very very simple to use. Simply include it on (for example) a search results page, and call it as normal (replacing current_page with the number of the current page, and total_pages with the total number of pages to display, or the variables holding those pieces of information), and the rest will be done for you.
If you wish to use something other than "current_page" as the variable name for the page number in the querystring, you will also need to change that in the script. The easiest way would be to do a simple find and replace on "current_page", though please do back your work up before doing any 'find and replace' work.
call do_pagination(current_page, total_pages)
The following code is based upon the PHP pagination code used in [url=http://www.phpbb.com]phpBB[/url], which is probably why the results may look familiar.
function do_pagination(current_page, total_pages)
current_page = cint(current_page)
dim url
dim strPages : strPages = ""
dim intMaxPages
dim intMinPages
dim intPaginI
' We start be building the URL to add the current_page variable to ... by removing the old current_page data
dim objRegExp : set objRegExp = new RegExp
objRegExp.Pattern = "(&|\?)?current_page=[^&]*(&|$)"
objRegExp.IgnoreCase = true
objRegExp.Global = true
url = objRegExp.replace(request.ServerVariables("SCRIPT_NAME") & "?" & request.ServerVariables("QUERY_STRING"), "$1")
set objRegExp = nothing
if (right(url, 1) = "&") then
url = left(url, len(url)-1)
end if
if (right(url, 1) = "?") then
url = left(url, len(url)-1)
end if
' Right, now we've got a clean url. Add a character to precede the new current_page value, and off we go!
if (instr(url, "?") > 0) then
url = url & "&"
else
url = url & "?"
end if
if (total_pages > 10) then
if (total_pages > 3) then
intMaxPages = 3
else
intMaxPages = total_pages
end if
for intPaginI = 1 to intMaxPages
if (intPaginI = current_page) then
strPages = strPages & "<strong>" & intPaginI & "</strong>"
else
strPages = strPages & "<a href=""" & url & "current_page=" & intPaginI & """>" & intPaginI & "</a>"
end if
if (intPaginI < intMaxPages) then
strPages = strPages & ", "
end if
next
if (total_pages > 3) then
if ((current_page > 1) and (current_page < total_pages)) then
if (current_page > 5) then
strPages = strPages & " ... "
else
strPages = strPages & ", "
end if
if (current_page > 4) then
intMinPages = current_page
else
intMinPages = 5
end if
if (current_page < total_pages - 4) then
intMaxPages = current_page
else
intMaxPages = total_pages - 4
end if
for intPaginI = intMinPages - 1 to intMaxPages + 1
if (intPaginI = current_page) then
strPages = strPages & "<strong>" & intPaginI & "</strong>"
else
strPages = strPages & "<a href=""" & url & "current_page=" & intPaginI & """>" & intPaginI & "</a>"
end if
if (intPaginI < intMaxPages + 1) then
strPages = strPages & ", "
end if
next
if (current_page < total_pages - 4) then
strPages = strPages & " ... "
else
strPages = strPages & ", "
end if
else
strPages = strPages & " ... "
end if
for intPaginI = total_pages - 2 to total_pages
if (intPaginI = current_page) then
strPages = strPages & "<strong>" & intPaginI & "</strong>"
else
strPages = strPages & "<a href=""" & url & "current_page=" & intPaginI & """>" & intPaginI & "</a>"
end if
if (intPaginI < total_pages) then
strPages = strPages & ", "
end if
next
end if
else
for intPaginI = 1 to total_pages
if (intPaginI = current_page) then
strPages = strPages & "<strong>" & intPaginI & "</strong>"
else
strPages = strPages & "<a href=""" & url & "current_page=" & intPaginI & """>" & intPaginI & "</a>"
end if
if (intPaginI < total_pages) then
strPages = strPages & ", "
end if
next
end if
do_pagination = strPages
end function

14 Comments
Could you explain a little better an example of how to use it?
#1, Drago, United States, 1 November 2006. Reply to this.
Drago i dont think the man should show you how to go to bathroom. He already show you how actually can paginate records in ASP. If you are a bedroom programmer like many others, I suggest you to try something else.
#2, A Man, Romania, 25 December 2006. Reply to this.
You suck dude.....its really disgusting the way u write this code...man you are just a baby...
#3, MANDALAY, Unknown, 16 May 2007. Reply to this.
Thanks for the intelligent, constructive criticism, Mandalay. Always nice to see smart people contributing.
#4, Dave Child, United Kingdom, 16 May 2007. Reply to this.
Great example, Dave. Thank you so much.
As for MANDALAY, grow up.
#5, Dylan Evans, United States, 3 July 2007. Reply to this.
<%@ Language="VBScript" EnableSessionState="True" %>
<% Option Explicit
server.ScriptTimeout=1000
Response.Buffer = True
%>
<!-- #include file="DbConMain.inc" -->
<%
Dim db
db=request.querystring("src")
if db="NIC" then
openCNMain
end if
if db <> "NIC" then
Response.Redirect("default.asp")
end if
%>
<html>
<head>
<meta name="VI60_defaultClientScript" content="VBScript">
<title>Invoice Creation</title>
<META http-equiv=Content-Type content="text/html; charset=windows-1252">
<META content=noindex,nofollow name=robots><LINK href="IEstyle.css" type=text/css rel=stylesheet>
<link href="IMAGES/stylesheet.css" rel="stylesheet" type="text/css">
<meta name="GENERATOR" content="Microsoft FrontPage 4.0">
<LINK REL="stylesheet" type="text/css" href="im/popcalendar.css" />
<script language="JavaScript" src="tigra_tables.js"></script>
<script language="javascript" type="text/javascript">
function submitt(thisform)
{
var invID = window.document.frm1.invoiceID.value;
if (invID == "")
{
alert("Please Enter Invoice Number");
window.document.frm1.invoiceID.focus();
return false;
}
else if(isNaN(invID))
{
alert("Invalid Entry, Only Numeric Values are Allowed!..");
window.document.frm1.invoiceID.focus();
return false;
}
else
{
return true;
}
}
</script>
</head>
<body leftmargin="0" topmargin="0" marginwidth="0" marginheight="0">
<table width="1100" border="0" align="center" cellpadding="0" cellspacing="0">
<tr>
<td width="38" rowspan="5" align="left" valign="top" bgcolor="#E4E4E4"></td>
<td width="929" height="26" align="left" valign="top" bgcolor="#E4E4E4"></td>
<td width="38" rowspan="5" align="left" valign="top" bgcolor="#E4E4E4"></td>
</tr>
<tr>
<td height="24"></td>
</tr>
<tr>
<td><table width="927" border="0" align="center" cellpadding="0" cellspacing="0">
<tr>
<td width="24" rowspan="3" align="left" valign="top"></td>
<td><table width="975" border="0" align="center" cellpadding="0" cellspacing="0">
<tr>
<td width="11"><img src="images/top_bar_lf.gif" width="11" height="102" /></td>
<td width="980" align="left" valign="middle" background="images/top_bar_mid.gif"><table width="854" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="236" align="left" valign="middle">
<a href="default.asp"><img src="images/logo.jpg" width="236" height="59" title="Home Page" border="0" /></a></td>
<td width="435" align="right" valign="middle"><table width="400" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="385" class="nTextB" >
<font color="#294B5F" >Invoice Creation</font></td>
</tr>
</table></td>
<td width="183" align="left" valign="top"><table width="183" border="0" align="center" cellpadding="0" cellspacing="0">
<tr>
<td> </td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td><table width="183" border="0" cellspacing="2" cellpadding="2">
<tr>
<td > </td>
</tr>
</table></td>
</tr>
</table></td>
</tr>
</table></td>
<td width="11"><img src="images/top_bar_rg.gif" width="11" height="102" /></td>
</tr>
</table></td>
<td width="24" rowspan="3" align="left" valign="top"></td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td width="100%" height="359" align="left" valign="top">
<!-- #include file="headerAdmin.asp" -->
<br>
<br>
<br>
<form name="frm1" method="post" onSubmit="return submitt(this);" action="dsp_view_delete_invoice.asp?src=NIC">
<table border="0" width="100%">
<tr>
<td width="69%"> </td>
<td width="20%" align="center">
<font color="#294B5F" face="Verdana" size="2">
<%
if Request.QueryString("Msg") <> "" then
Response.Write("<strong>No Records To Display</strong>")
end if
%>
</font>
</td>
<td> </td>
</tr>
<tr>
<td align="right" colspan="2">
<font face="Verdana" size="2"><strong>Enter Invoice Number</strong></font>
<input name="invoiceID" type="text" class="txt" title="Enter Invoice Number" tabindex="1">
</td>
<td width="11%">
<input type="submit" name="Submit Invoice Number" value="Go" title="Go" class="btnStyle" tabindex="2"/>
</td>
</tr>
</table>
</form>
<table cellpadding="2" cellspacing="2" align="center" width="95%">
<tr>
<td colspan="6" align="center">
<font color="#294B5F" face="Verdana" size="2">
<%
if Request.QueryString("Del") <> "" then
Response.Write("<strong>Record Deleted Successfully</strong>")
end if
%>
</font>
</td>
</tr>
<tr>
<td colspan="6"> </td>
</tr>
</table>
<table cellpadding="2" cellspacing="2" align="center" width="95%" id="Invoice Details">
<tr bgcolor="#e4e4e4" height="25" class="nTextH">
<th nowrap>Invoice Id</th>
<th nowrap>Program</th>
<th nowrap>Module</th>
<th nowrap>Create Date</th>
<th nowrap>From Date</th>
<th nowrap>To Date</th>
</tr>
<%
dim rsInvoice,qryInvoice
set rsInvoice=Server.CreateObject("ADODB.RecordSet")
qryInvoice="SELECT invoice_Details.invoiceID, Portfolio.portfolioName, Program.programName, Project.projectName,ModuleList.moduleName, invoice_Details.createdate, invoice_Details.fromDate, invoice_Details.toDate, invoice_Details.toAddress FROM (Program INNER JOIN (Project INNER JOIN (invoice_Details INNER JOIN ModuleList ON invoice_Details.moduleID = ModuleList.moduleID) ON Project.projectID = ModuleList.projectID) ON Program.programID = Project.programID) INNER JOIN Portfolio ON Program.portfolioID = Portfolio.portfolioID ORDER BY invoice_Details.invoiceID"
Dim thisPage, rowcount, TotalPages, pgSise, RecCount
Const adOpenStatic = 3
thisPage = Trim(Request("thisPage"))
if thisPage = "" then thisPage = 1
rsInvoice.CursorType = adOpenStatic
rsInvoice.PageSize = 10
rsInvoice.Open qryInvoice,con,1,3
if not rsInvoice.EOF then
rsInvoice.AbsolutePage = cINT(thisPage)
end if
TotalPages = rsInvoice.PageCount
pgSise = rsInvoice.PageSize
RecCount = rsInvoice.RecordCount
'Response.Write(TotalPages&"<br>")
rowCount = 0
If Not rsInvoice.EOF then
Do While Not rsInvoice.EOF and rowCount < pgSise
%>
<tr>
<td nowrap class='nText'>
<a href="dsp_view_delete_invoice.asp?src=NIC&invoiceID=<%=rsInvoice(0)%>&val=List&thisPage=<%=thisPage%>" class="namelink" title="Click Here To View Detailed Invoice Details"><%=rsInvoice(0)%></a>
</td>
<td nowrap class='nTextL'> <%=rsInvoice(2)%></td>
<td nowrap class='nTextL'> <%=rsInvoice(4)%></td>
<td nowrap class='nText'>
<%=DatePart("d",rsInvoice(5))%>-<%=monthname(DatePart("m",rsInvoice(5)),true)%>-<%=DatePart("yyyy",rsInvoice(5))%>
</td>
<td nowrap class='nText'>
<%=DatePart("d",rsInvoice(6))%>-<%=monthname(DatePart("m",rsInvoice(6)),true)%>-<%=DatePart("yyyy",rsInvoice(6))%>
</td>
<td nowrap class='nText'>
<%=DatePart("d",rsInvoice(7))%>-<%=monthname(DatePart("m",rsInvoice(7)),true)%>-<%=DatePart("yyyy",rsInvoice(7))%>
</td>
</tr>
<%
rsInvoice.movenext
rowCount = rowCount + 1
Loop
else
%>
<tr>
<td colspan="6" align="center">
<font color="#800000" face="Verdana" size="2"><b>Sorry ! No Records To Display</b></font>
</td>
</tr>
<%
end if
%>
</table>
<script language="JavaScript">
<!--
tigra_tables('Invoice Details', 1, 0, '#e5e5e5', '#F9F9F9', '#ffccff', '#cc99ff');
// -->
</script>
<%
If TotalPages > 1 then
CALL Pagination(thisPage, TotalPages)
End if
%>
<%
Function Pagination(thisPage, TotalPages)
thisPage = cint(thisPage)
Dim url, MaxPages, MinPages, CurrPage, vUrl
Dim strPages : strPages = ""
vUrl = "invoice_list.asp?src=NIC&"
IF (TotalPages > 10) THEN 'Main IF
if (TotalPages > 3) then
MaxPages = 3
else
MaxPages = TotalPages
end if
for CurrPage = 1 to MaxPages
if (CurrPage = thisPage) then
strPages = strPages & "<font face=Verdana size=2px; color=#C00221><strong>"&CurrPage&"</strong></font>"
else
strPages = strPages & "<a href="&vUrl&"thisPage="&CurrPage&" class=namelink>"&CurrPage&"</a>"
end if
if (CurrPage < MaxPages) then
strPages = strPages & " "
end if
next
if (TotalPages > 3) then 'If Sub if 1
if ((thisPage > 1) and (thisPage < TotalPages)) then 'If Sub if 2
if (thisPage > 5) then
strPages = strPages & " . . . "
else
strPages = strPages & " "
end if
if (thisPage > 4) then
MinPages = thisPage
else
MinPages = 5
end if
if (thisPage < TotalPages - 4) then
MaxPages = thisPage
else
MaxPages = TotalPages - 4
end if
for CurrPage = MinPages - 1 to MaxPages + 1
if (CurrPage = thisPage) then
strPages = strPages & "<font face=Verdana size=2px; color=#C00221><strong>"&CurrPage&"</strong></font>"
else
strPages = strPages & "<a href="&vUrl&"thisPage="&CurrPage&" class=namelink>"&CurrPage&"</a>"
end if
if (CurrPage < MaxPages + 1) then
strPages = strPages & " "
end if
next
if (thisPage < TotalPages - 4) then
strPages = strPages & " . . . "
else
strPages = strPages & " "
end if
else
strPages = strPages & " . . . "
end if 'End If Sub if 2
for CurrPage = TotalPages - 2 to TotalPages
if (CurrPage = thisPage) then
strPages = strPages & "<font face=Verdana size=2px; color=#C00221><strong>"&CurrPage&"</strong></font>"
else
strPages = strPages & "<a href="&vUrl&"thisPage="&CurrPage&" class=namelink>"&CurrPage&"</a>"
end if
if (CurrPage < TotalPages) then
strPages = strPages & " "
end if
next
end if 'End If Sub IF 1
else
for CurrPage = 1 to TotalPages
if (CurrPage = thisPage) then
strPages = strPages & "<font face=Verdana size=2px; color=#C00221><strong>"&CurrPage&"</strong></font>"
else
strPages = strPages & "<a href="&vUrl&"thisPage="&CurrPage&" class=namelink>"&CurrPage&"</a>"
end if
if (CurrPage < TotalPages) then
strPages = strPages & " "
end if
next
End IF 'Mail End IF
Pagination = strPages
Dim DecthisPage,IncthisPage
DecthisPage = thisPage - 1
IncthisPage = thisPage + 1
'Response.Write(DecthisPage&"<br>")
'Response.Write(thisPage&"<br>")
'Response.Write(IncthisPage&"<br>")
Response.Write("<table cellpadding=2 cellspacing=2 align=center width=95% border=0>")
Response.Write("<tr>")
Response.Write("<td>")
Response.Write(" ")
Response.Write("</td>")
Response.Write("</tr>")
Response.Write("<tr>")
Response.Write("<td colspan=6 align=center>")
if thisPage > 1 then
Response.Write("<a href="&vUrl&"thisPage="&DecthisPage&" class=namelink>Previous</a> ")
end if
Response.Write(Pagination)
if IncthisPage <= TotalPages then
Response.Write(" <a href="&vUrl&"thisPage="&IncthisPage&" class=namelink>Next </a>")
end if
Response.Write("</td>")
Response.Write("</tr>")
Response.Write("</table>")
End Function
%>
<!---->
</td>
</tr>
</table></td>
</tr>
<tr>
<td height="24"></td>
</tr>
<tr>
<td height="38" align="center" valign="middle" bgcolor="#E4E4E4" class="top-txt">© Copyright Celunite Inc. 2006-<%=year(now)%></td>
</tr>
</table>
<%
rsInvoice.Close
Set rsInvoice = Nothing
con.Close
%>
</body>
</html>
#6, Varun Reddy, India, 27 September 2007. Reply to this.
and the DbConMain.inc includes
<object progid="adodb.connection" id=con runat=server></object>
<script Language=VBScript RunAt=Server>
Sub openCNMain
con.Provider = "Microsoft.jet.oledb.4.0"
'response.write con.State
If con.State=1 Then con.close
con.Open server.MapPath( "final.mdb")
End Sub
Sub closeCNMain
If con.State=1 Then
con.close
set con = Nothing
end if
End Sub
</script>
#7, Varun Reddy, India, 27 September 2007. Reply to this.
Use this for Pagination. I made necessary modifications so that every one can use it.
#8, Varun Reddy, India, 27 September 2007. Reply to this.
Cheers Dave, once more you have removed a little pain from my day- i recall seeing this function years back on a site of yours i worked at back at the egg- was hoping it would appear on here somewhere!
#9, Shawson, United Kingdom, 19 February 2008. Reply to this.
Ahh Frontpage *runs far away*
<meta name="GENERATOR" content="Microsoft FrontPage 4.0">
#10, Jason, United Kingdom, 21 February 2008. Reply to this.
i worked on ur code. everything worked right.
But my whole data(1387 rows) is displaying only on the 1st page.
help me!
Thanx in advance
#11, vipin, Unknown, 17 April 2008. Reply to this.
Thank you for the code, and not only the code but also your clearity. I've seen many codes just completely unclear and unclean, not properly spaced and hard to read, but yours is very easy to read and easily implemented.
One suggestion would be to put comments in the code so that developers like myself can easily make changes if need be
#12, Brett, Unknown, 19 September 2008. Reply to this.
hey DC --
spanks again for a great chunk of coding goodness. This pager + plus your date formatting code has saved my sorry azz several hours, yet again! ( date functs here: http://www.addedbytes.com/asp/vbscript-date-format-functions/ )
spanks a mill, dave-y doo! 1st Jack & coke's on me if we ever meet up, mate.
d
#13, dave too (II), United States, 13 December 2008. Reply to this.
Mandalay may have put it in an ignorant manner, but he was correct - that code is sloppy as hell. I'd like to round up all the sloppy web developers and punch them in the face, one by one.
#14, Joe, Unknown, 24 March 2009. Reply to this.