Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 31 additions & 1 deletion MysqliDb.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
// END class
10 changes: 4 additions & 6 deletions dbObject.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

/**
Expand Down
11 changes: 11 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down