From c96e057e3f55404e0b165e7fefed01874836eb00 Mon Sep 17 00:00:00 2001 From: williamnixon20 <75229742+williamnixon20@users.noreply.github.com> Date: Mon, 2 Oct 2023 14:44:46 +0700 Subject: [PATCH] fix pagination with search query --- src/bases/BaseRepository.php | 18 ++++++++++++++++-- src/controllers/cat/CatController.php | 6 +++--- src/services/CatSrv.php | 4 ++-- 3 files changed, 21 insertions(+), 7 deletions(-) diff --git a/src/bases/BaseRepository.php b/src/bases/BaseRepository.php index 32c1ac2..4027939 100644 --- a/src/bases/BaseRepository.php +++ b/src/bases/BaseRepository.php @@ -85,12 +85,26 @@ abstract class BaseRepository $query .= " LIMIT $perPage OFFSET $offset"; } - echo $query; $stmt = $this->pdo->prepare($query); $stmt->execute(); - return $stmt->fetchAll(PDO::FETCH_ASSOC); + $results = $stmt->fetchAll(PDO::FETCH_ASSOC); + + + $countQuery = "SELECT COUNT(*) as total FROM $this->tableName"; + if (!empty($where)) { + $countQuery .= " WHERE " . implode(" AND ", $where); + } + + $stmtCount = $this->pdo->prepare($countQuery); + $stmtCount->execute(); + $totalCount = $stmtCount->fetch(PDO::FETCH_ASSOC)['total']; + + return [ + 'count' => $totalCount, + 'result' => $results, + ]; } public function update($id_col, $id, $data, $paramTypes) diff --git a/src/controllers/cat/CatController.php b/src/controllers/cat/CatController.php index 5676199..e30fc73 100644 --- a/src/controllers/cat/CatController.php +++ b/src/controllers/cat/CatController.php @@ -38,11 +38,11 @@ class CatController extends BaseController "pageSize" => $_GET['pageSize'] ?? null, "isDesc" => $_GET['isDesc'] ?? null ]); - $_count = $this->srv->countCats()[0]; - $responseCats = array_map(function ($cat) { return $cat->toResponse(); - }, $cats); + }, $cats["result"]); + + $_count = $cats["count"]; // Include the HTML template require_once PROJECT_ROOT_PATH . "/public/view/cats.php"; diff --git a/src/services/CatSrv.php b/src/services/CatSrv.php index 275829a..e29c6d3 100644 --- a/src/services/CatSrv.php +++ b/src/services/CatSrv.php @@ -49,11 +49,11 @@ class CatSrv extends BaseSrv $catsResult = $this->repository->select('*', $where, $order, $config["pageNo"], $config['pageSize'], $config['isDesc']); $cats = []; - foreach ($catsResult as $catResult) { + foreach ($catsResult["result"] as $catResult) { $cat = new CatModel(); $cats[] = $cat->constructFromArray($catResult); } - return $cats; + return ["result" => $cats, "count" => $catsResult["count"]]; } public function createCat($catData) -- GitLab