PHPBuilder - Building Next/Prev Buttons for Query Results Page 2

RSS Twitter

Building Next/Prev Buttons for Query Results - Page 2

by: Rod Kreisler
December 13, 2000

The $where variable is a little difficult to explain. If your code generates a dynamic where clause based upon data passed to the script, you will need to construct the $where variable. It is not entirely safe to pass the EXACT where clause in the query string of the URL, so you can "encode" the where clause. NOTE: if your where clause is entirely static (i.e. is always the same for each instance of the script) or your query does not utilize a where clause you need do nothing.
For example, let's say our where clause is based on two variables passed to the script: $one and $two, and would be used in the following manner in the where clause of our query:
where one='$one' and two='$two'
We would want to add this code somewhere at the top of the script:


if (!$where// where was not passed {
if (empty($one) || empty($two)) {
// some error handling as $one 
        //and/or $two not passed to initial page
// NOTE: if a pipe (|) may be in the value 
//of $one or $two, use a different delimiter
$query_where="where one='$data[0]' AND two='$data[1]'";

How this will be used will become clear in a moment. NOTE: if you do not have a where clause, do not use the above code in your script. No modificatins to the function are neccesary however.
The last variable we need is $numpage, which is the number of pages that will display. In short, it is the number of records divided by $limit, rounded up. We need to preform two queries for this operation to work successfully. The first query returns the number of rows that would be returned without a limit:


=mysql_query("select count(*) from tablename $query_where");
#calc num pages
if (
$numrec%$limit$numpage++; // add one page if remainder

Now, we can do our query that returns the actual records we will display:


=mysql_query("select * from tablename $query_where limit $offset,$limit");

The only thing remaining is to call the function. But what if our query is limited in such a way as there will only be one set of results? We certainly don't want to display page links if there are no other pages!


if ($numpage>1) {

will solve this problem.

« Previous Page
Next Page »

Comment and Contribute

Your comment has been submitted and is pending approval.

Rod Kreisler



(Maximum characters: 1200). You have characters left.