This function returns an array of 3 values that makes browsing through your SQL results, or any other list of results, very easy. The navigation bar looks very similar to ones used in most sites [ prev 6 7 8 9 10 next ]. You can limit the amount of rows displayed, the amount of page numbers to display, the previous and next buttons/text. etc.
By : vicus
<?
/*
******************************
* Easy Result Navigator 1.3 *
******************************
Author: Wikus Stander
wikus[at]iamdev[dot]com
http://www.iamdev.com
_ __
(_)__ ___ _ ___/ /__ _ __ _______ __ _
/ / _ `/ ' \/ _ / -_) |/ /_ / __/ _ \/ ' \
/_/\_,_/_/_/_/\_,_/\__/|___/(_)\__/\___/_/_/_/
Copyright:
You may use this function freely. I hope you will
respect the author's intellectual property by:
- keeping this notice in your source, and
- dropping the author a mail: wikus[at]iamdev[dot]com
Thanx.
-------
Changes
-------
01-09-2003: In my example I rather suggest using the COUNT(*) function in the first
SQL query instead of mysql_num_rows(). This would make it return the 'totalrows'
value much faster, especially when there are lots of rows to return..
17-02-2003: Fixed a few bugs when using the next previous links (It would forget the
mysql limit position, etc.) I've removed an argument (start), and you cannot click
on the current selected page anymore. So a few less lines of code and arguments
that makes all the difference. enjoy :)
22-01-2003: Changed variables used in the example at the end of this document to
the global $_GET array. I found most users are running php with register_globals
turned off (php.ini). Thanx Tim Noble for the email :)
-----
To Do
-----
I've had some requests for making it support MSSQL (MSSQL doesn't support the LIMIT
clause) But I'm sure there is a way to get around it :) Keep checking this page...
-----------
Description
-----------
The function returns an array of 3 values as described below:
VALUE 1 [0]: Returns a string that can be appended to your SQL query so that the
correct block of rows can be returned. Eg. " LIMIT 10, 20"
VALUE 2 [1]: Returns an html string that gives the user an indication of which rows
he's currently browsing. Eg. 11-20
VALUE 3 [2]: Returns an html navigation bar needed for navigating through the total
result returned Eg. Page: << 6 7 8 9 10 >>
---------
Arguments
---------
The first 4 arguments are declared/assigned by you while the last 3 are done when
you start using the navigation bar generated by the function (See 'Usage' below).
totalrows - The TOTAL amount of rows returned by your executed SQL statement
numLimit - The amount of page numbers you'd like displayd in your navigation bit
Eg. '4' would display "Page: 1 2 3 4 Next 4 >>"
amm - The amount of rows returned per page (for the SQL string to append)
queryStr - If you'd like extra vars to be passed to that page Eg. "&name=value"
There are also 3 variables inside the function you can change if you'd like the
navigation bar to look a little different (larrow,rarrow,wholePiece).
-----
Usage
-----
See 'Usage' at the end of this document.
*/
function pageBrowser($totalrows,$numLimit,$amm,$queryStr,$numBegin,$begin,$num) {
$larrow = " << Prev ".$numLimit." "; //You can either have an image or text, eg. Previous
$rarrow = " Next ".$numLimit." >> "; //You can either have an image or text, eg. Next
$wholePiece = "Page: "; //This appears in front of your page numbers
if ($totalrows > 0) {
$numSoFar = 1;
$cycle = ceil($totalrows/$amm);
if (!isset($numBegin) || $numBegin < 1) {
$numBegin = 1;
$num = 1;
}
$minus = $numBegin-1;
$start = $minus*$amm;
if (!isset($begin)) {
$begin = $start;
}
$preBegin = $numBegin-$numLimit;
$preStart = $amm*$numLimit;
$preStart = $start-$preStart;
$preVBegin = $start-$amm;
$preRedBegin = $numBegin-1;
if ($start > 0 || $numBegin > 1) {
$wholePiece .= "<a href='?num=".$preRedBegin
."&numBegin=".$preBegin
."&begin=".$preVBegin
.$queryStr."'>"
.$larrow."</a>\n";
}
for ($i=$numBegin;$i<=$cycle;$i++) {
if ($numSoFar == $numLimit+1) {
$piece = "<a href='?numBegin=".$i
."&num=".$i
."&begin=".$start
.$queryStr."'>"
.$rarrow."</a>\n";
$wholePiece .= $piece;
break;
}
$piece = "<a href='?begin=".$start
."&num=".$i
."&numBegin=".$numBegin
.$queryStr
."'>";
if ($num == $i) {
$piece .= "</a><b>$i</b><a>";
} else {
$piece .= "$i";
}
$piece .= "</a>\n";
$start = $start+$amm;
$numSoFar++;
$wholePiece .= $piece;
}
$wholePiece .= "\n";
$wheBeg = $begin+1;
$wheEnd = $begin+$amm;
$wheToWhe = "<b>".$wheBeg."</b> - <b>";
if ($totalrows <= $wheEnd) {
$wheToWhe .= $totalrows."</b>";
} else {
$wheToWhe .= $wheEnd."</b>";
}
$sqlprod = " LIMIT ".$begin.", ".$amm;
} else {
$wholePiece = "Sorry, no records to display.";
$wheToWhe = "<b>0</b> - <b>0</b>";
}
return array($sqlprod,$wheToWhe,$wholePiece);
}
/*
+-------+
| Usage |
+-------+
NOTE!: This is just an example and WON'T WORK if you include
this in your code, comment it out or delete it :)
*/
$criterea = " WHERE column=value AND column_2=value_2";
$sql = "SELECT COUNT(*) AS totalrows FROM table".$criterea;
//get the total amount of rows returned
$arr = mysql_fetch_array(mysql_query($sql));
/*
Call the function:
I've used the global $_GET array as an example for people
running php with register_globals turned 'off' :)
*/
$navigate = pageBrowser($arr[totalrows],10,10,"&name=value",$_GET[numBegin],$_GET[begin],$_GET[num]);
//execute the new query with the appended SQL bit returned by the function
$sql = "SELECT * FROM table".$criterea.$navigate[0];
$rs = mysql_query($sql);
//the indication of which rows are being browsed. Eg. listing 1-10 of 100 results.
echo "<p>Listing ".$navigate[1]." of ".$totalrows." results.</p>";
//the navigation bar returned by the function
echo "<p>".$navigate[2]."</p>";
//loop and display the limited records being browsed
while ($arr = mysql_fetch_array($rs)) {
echo $arr[column_1]." ".$arr[column_2]."<br>";
}
//the navigation bar at the bottom again
echo "<p>".$navigate[2]."</p>";
/*
I hope this can come in handy :)
*/
?>
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |
More Site Navigation Code Articles
More By Codewalkers
developerWorks - FREE Tools! |
As businesses grow increasingly dependent upon Web applications to provide services to customers, employees and partners, these complex applications become more difficult to secure. Although traditional security solutions protect Internet infrastructure layers, they do not guard against HTTP and HTML attacks. Many organizations that conduct security testing still deploy applications that allow attackers to manipulate their logic and wreak havoc on their business. To mitigate this risk, development and delivery teams must address Web application security throughout the lifecycle, addressing the many layers detailed in this paper. FREE! Go There Now!
|
|
|
|
You probably have thousands of lines of COBOL code loaded with business intelligence and being used to run your business, along with an army of developers maintaining these applications. Learn how to prepare your applications and developers so you can keep that competitive edge and move to a service-oriented architecture with the IBM Rational Enterprise Modernization solutions. Replay is available for 9 months. FREE! Go There Now!
|
|
|
|
Build secure Web services with transport-level security using IBM Rational Application Developer V7 and IBM WebSphere Application Server V6.1. Follow this three-part series for step-by-step instructions about how to develop Web services and clients, configure HTTP basic authentication, and configure HTTP over SSL (HTTPS). This first part of the series walks you through building a Web service for a simple calculator application. You generate and test two different types of Web services clients: a Java Platform, Enterprise Edition (Java EE) client and a stand-alone Java client. You also handle user-defined exceptions in Web services. FREE! Go There Now!
|
|
|
|
Visit IBM developerWorks to download a free trial version of WebSphere Business Modeler Advanced V6.1.1, IBM’s premier business process modeling and analysis tool for business users that offers process modeling, simulation, and analysis capabilities. IBM WebSphere Business Modeler helps you visualize, understand, and document business processes for continuous improvement. FREE! Go There Now!
|
|
|
|
Visit IBM developerWorks to download the latest trial version of IBM Data Studio V1.1 at no cost. IBM Data Studio is a comprehensive data management solution that helps you effectively design, develop, deploy and manage your data, databases, and database applications throughout the data management life cycle utilizing a consistent and integrated user interface. Unlike other client-side data management solutions that focus on only one aspect of the application lifecycle or database administration, Data Studio complements the Rational Software Delivery platform, providing unparalleled flexibility for a heterogeneous data server environment across platforms. FREE! Go There Now!
|
|
|
|
Asset Reuse is a key strategy for companies looking to create innovative solutions to solve complex software development problems. Searching for, identifying, updating, using and deploying software assets can be a difficult challenge. Listen to this webcast, to learn about strategies and tools that you can leverage for a successful project, including Rational Asset Manager, Rational Software Architect and WebSphere Service Registry and Repository. FREE! Go There Now!
|
|
|
|
Learn the basics of the IBM Customer Information Control System (CICS). With a hands-on exercise, learn how to get your first CICS application up and running on your desktop using TXSeries V6.1 for Windows. The tutorial shows you how to download and install a free trial version of TXSeries V6.1. FREE! Go There Now!
|
|
|
|
As organizations have grown increasingly dependent on online software, the risk of malicious attacks has also become far more serious. Fortunately, well-governed organizations can protect their Web applications by injecting vulnerability assessments and ethical hacks into their software development and delivery processes. This paper describes 12 of the most common hacker attacks and provides basic rules that you can follow to help create more hack-resistant Web applications. FREE! Go There Now!
|
|
|
|
Try the latest version of IBM Rational Manual Tester V7.0.1 by downloading a free trial from IBM developerWorks. This manual test authoring and execution tool promotes test step reuse to reduce the impact of software change on testers and business analysts and addresses the needs of teams performing at least a portion of their testing manually. FREE! Go There Now!
|
|
|
|
WebSphere Process Server delivers a unique integration framework that simplifies existing IT resources. Often, as IT assets grow to support business demand, so too does their complexity and manageability. In this webcast, we’ll discuss how WebSphere Process Server helps deliver an SOA infrastructure that provides a common model to orchestrate, mediate, connect, map, and execute the underlying IT functions. Discover how WebSphere Process Server simplifies integration of business processes by leveraging existing IT assets as reusable services without the complexities of traditional integration methodologies. FREE! Go There Now!
|
|
|
|
All FREE IBM® developerWorks Tools! |