Reputation: 13462
Hello so I am using slim framework together with PDO connection and is having a big(for me) problem. I wanted to switch with eloquent orm instead of normal try and catching PDO but 45% is already done in my project. So this is my sample code so far
$app->get('/data', function () use ($app) {
try {
$data = $stmt->query("SELECT * FROM tableName");
} catch(PDOException $e) {
die('Error.');
}
$app->render('data.html', array(
'data' => $data
));
});
How can I put pagination with slim framework? Is there a solution to this? Thank you!
Upvotes: 1
Views: 7781
Reputation: 3408
You could provide some Parameter to your route - I'm not sure about the current syntax in Slim2, so i will explain this with GET params.
/data
No paginate param is set so this would be the first page - provide default params.
/data?page=2&limit=10
Page 2 - Limit is optional (but the default for this is required). With that params you can "calculate" where your dataset is.
//not tested
$app->get('/data', function () use ($app) {
//pls validate that are numbers
$page = (isset($_GET['page']) && $_GET['page'] > 0) ? $_GET['page'] : 1;
$limit = isset($_GET['limit']) ? $_GET['limit'] : 10;
$offset = (--$page) * $limit; //calculate what data you want
//page 1 -> 0 * 10 -> get data from row 0 (first entry) to row 9
//page 2 -> 1 * 10 -> get data from row 10 to row 19
$countQuery = $stmt->prepare('SELECT COUNT(*) FROM table');
$dataQuery = $stmt->prepare('SELECT * FROM table LIMIT :limit OFFSET :offset');
$dataQuery->bindValue(':limit', $limit, \PDO::PARAM_INT);
$dataQuery->bindValue(':offset', $offset, \PDO::PARAM_INT);
try {
$count = $countQuery->execute();
$data = $dataQuery->execute();
} catch(PDOException $e) {
die('Error.');
}
$app->render('data.html', array(
'data' => $data,
'count' => $count
));
});
For better handling you could write a simple Pagination helper class.
Upvotes: 5
Reputation: 4254
How can I put pagination with slim framework?
You can probably use Zend Paginator http://framework.zend.com/manual/2.3/en/modules/zend.paginator.usage.html . See @mwop own Paginator class and how he does this https://github.com/weierophinney/mwop.net/blob/266eea772717f681936d06425e85bc008a22b6e8/src/Blog/PdoPaginator.php
There is another one https://github.com/whiteoctober/Pagerfanta . You can try one of them.
Regarding your question about moving to Eloquent, it is upto you.
Thank you
Upvotes: -1