From 7d08fbcc7059107bdb06e4b7ab03d49488af0170 Mon Sep 17 00:00:00 2001 From: Alexander Butenko Date: Sun, 15 Nov 2015 12:28:23 +0300 Subject: [PATCH] added paginate() to mysqlidb --- MysqliDb.php | 32 +++++++++++++++++++++++++++++++- dbObject.php | 10 ++++------ readme.md | 11 +++++++++++ 3 files changed, 46 insertions(+), 7 deletions(-) diff --git a/MysqliDb.php b/MysqliDb.php index 9c21ad03..5697702a 100644 --- a/MysqliDb.php +++ b/MysqliDb.php @@ -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 @@ public function map($idField) $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 diff --git a/dbObject.php b/dbObject.php index b5fbc0a9..1290d718 100644 --- a/dbObject.php +++ b/dbObject.php @@ -427,12 +427,10 @@ protected function count () { * @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; } /** diff --git a/readme.md b/readme.md index 21c03aa4..b29d7e0c 100644 --- a/readme.md +++ b/readme.md @@ -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.