Commit 7d08fbcc authored by Alexander Butenko's avatar Alexander Butenko

added paginate() to mysqlidb

parent d5478582
......@@ -180,6 +180,20 @@ class MysqliDb
protected $traceStripPrefix;
public $trace = array();
/**
* Per page limit for pagination
*
* @var int
*/
public $pageLimit = 20;
/**
* Variable that holds total pages count of last paginate() query
*
* @var int
*/
public $totalPages = 0;
/**
* @param string $host
* @param string $username
......@@ -1838,6 +1852,22 @@ class MysqliDb
$this->_mapKey = $idField;
return $this;
}
/**
* Pagination wraper to get()
*
* @access public
* @param string $table The name of the database table to work with
* @param int $page Page number
* @param array|string $fields Array or coma separated list of fields to fetch
* @return array
*/
public function paginate ($table, $page, $fields = null) {
$offset = $this->pageLimit * ($page - 1);
$res = $this->withTotalCount()->get ($table, Array ($offset, $this->pageLimit), $fields);
$this->totalPages = round($this->totalCount / $this->pageLimit);
return $res;
}
}
// END class
\ No newline at end of file
// END class
......@@ -427,12 +427,10 @@ class dbObject {
* @return array
*/
private function paginate ($page, $fields = null) {
$offset = self::$pageLimit * ($page - 1);
$this->db->withTotalCount();
$results = $this->get (Array ($offset, self::$pageLimit), $fields);
self::$totalPages = round ($this->db->totalCount / self::$pageLimit);
return $results;
$this->db->pageLimit = self::$pageLimit;
$res = $this->db->paginate ($this->dbTable, $page, $fields);
self::$totalPages = $this->db->totalPages;
return $res;
}
/**
......
......@@ -198,6 +198,17 @@ foreach ($logins as $login)
echo $login;
```
###Pagination
Use paginate() instead of get() to fetch paginated result
```php
$page = 1;
// set page limit to 2 results per page. 20 by default
$db->pageLimit = 2;
$products = $db->arraybuilder()->paginate("products", $page);
echo "showing $page out of " . $db->totalPages;
```
### Result transformation / map
Instead of getting an pure array of results its possible to get result in an associative array with a needed key. If only 2 fields to fetch will be set in get(),
method will return result in array($k => $v) and array ($k => array ($v, $v)) in rest of the cases.
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment