PHP Classes

File: QueryLimit.class.php

Recommend this page to a friend!
  Classes of Eren Ezgü   Query Limit   QueryLimit.class.php   Download  
File: QueryLimit.class.php
Role: Class source
Content type: text/plain
Description: QueryLimit class file
Class: Query Limit
Compute the LIMIT clause to get paginated results
Author: By
Last change: Accessible without user login
Date: 15 years ago
Size: 2,229 bytes
 

Contents

Class file image Download
<?
/**
* @desc A simple class for getting the LIMIT part of a query for paging
* The class needs 3 values : total rows, rows per page, page number to get results for (page number starts from 1)
* @author Eren Ezgü < eezgu at eezgu com >
* @version 0.1
* @example

        $params = array('total_rows'=>40,'page_size'=>5,'page'=>6);

        $pager = new QueryLimit($params);

        if($limit_string = $pager->getLimitString() ){
            // ...
            mysql_query("SELECT * FROM `table` {$limit_string} ");
            // ...
        }
        else{
            // there is a problem
            echo $pager->error;
        }
*/
class QueryLimit{

    var
$error ='';

    var
$data = array(
       
'total_rows'=>0,
       
'page_size'=>10,
       
'page'=>1
   
);

    var
$limit_string = '';
    var
$limits = array(0,0);
    var
$total_pages = 0;

    function
QueryLimit($params=array()){
        foreach(
$params as $param=>$val){
            if(isset(
$this->data[$param])){
               
$this->data[$param] = intval($val);
            }
        }
       
$this->limits[1]=$this->data['page_size'];
    }

    function
getLimitString(){
        if(
$this->data['page_size']<1){
           
$this->error = 'Page size (rows per page) must be greater than 0';
            return
false;
        }
       
$this->total_pages = ($this->data['total_rows']==0)?'1': ceil($this->data['total_rows']/$this->data['page_size']);
        if(
$this->data['page']<1 || $this->data['page']>$this->total_pages){
           
$this->error = 'Invalid page number';
            return
false;
        }

       
$this->limits[0] = $this->data['page_size']*($this->data['page']-1);
        return (
$this->limit_string = ' LIMIT '.implode(',',$this->limits).' ');
    }

    function
getTotalPages(){
        return
$this->$total_pages;
    }

    function
setPageSize($page_size){
       
$this->data['page_size']=intval($page_size);
    }

    function
setPage($p){
       
$this->data['page']=intval($p);
    }

    function
nextPage(){
       
$this->data['page']++;
    }

    function
previousPage(){
       
$this->data['page']--;
    }

}
?>