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



RSS Twitter
Articles Databases

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:

<?php

if (!$where// where was not passed {
    
if (empty($one) || empty($two)) {
           
// some error handling as $one 
        //and/or $two not passed to initial page
    
}
    
$where="$one|$two";
}
// NOTE: if a pipe (|) may be in the value 
//of $one or $two, use a different delimiter
$data=explode('|',$where); 
$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:

<?php

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

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

<?php

$result
=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!

<?php

if ($numpage>1) {
    
pagenav();
    print 
"<P>";
}

?>
will solve this problem.

« Previous Page
1
|
2
|
3
Next Page »

Comment and Contribute

Your comment has been submitted and is pending approval.

Author:
Rod Kreisler

Comment:



Comment:

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