Reputation: 663
I'm new to yii. Currently I am building an API for some project. I managed to get all data from the database and sent as a response to the front end. Now there is an enhancement that I should limit the results outputted per page. So Pagination. I read a lot on CPagination in yii and no matter what I tried I'm getting a 500 internal server error. This is my codes;
public function actionIndex()
{
//getting page number from front end
$request = file_get_contents('php://input');
if (is_null($request)) {
$page = 1;
} else {
$input = json_decode($request, true);
$page = $input['page'];
}
//Criteria sorting templates by id DESC
$criteria = new CDbCriteria;
$criteria->order = 'id DESC';
//Number of rows returned
$count = TblTemplate::model()->count($criteria);
//Templates per page
$perPage = 2;
//Calculating the offset
$offset = ($page > 1) ? ($page * $perPage) - $perPage : 0;
$pages = new CPagination($count);
$pages->pageSize = $perPage;
$pages->offset = $offset;
$pages->applyLimit($criteria);
//fetching all templates
$templates = TblTemplate::model()->findAll($criteria);
$response = [];
//Fetching all array - filtering through the cluster
foreach ($templates as $template) {
$response[] = [
'id' => $template->id,
'name' => $template->name,
'email' => $template->email,
'content' => $template->content
];
}
echo json_encode($response);
}
Thanks for your help.
Upvotes: 1
Views: 605
Reputation: 4160
Change It as: -
$perPage = 2;
$offset = ($page > 1) ? ($page * $perPage) - $perPage : 0;
$criteria = new CDbCriteria;
$criteria->order = 'id DESC';
$criteria->limit=$perPage;
$criteria->offset=$offset;
$templates = Users::model()->findAll($criteria);
Upvotes: 1