Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- function fetchPost($table): object
- {
- $data = [];
- try {
- $this->db->query("SELECT id, title, body FROM $table ORDER BY id DESC ");
- $rows = $this->db->fetchAll();
- // Map the data and apply changes
- $data = array_map(static function ($row) {
- return $row;
- }, $rows);
- // Or directly apply rows to the data
- $data = $this->db->fetchAll();
- } catch (Exception $e) {
- return (object)[
- 'error' => true,
- 'message' => sprintf(
- 'Check %s class on %s method: %s',
- 'SelectPosts',
- __METHOD__,
- $e->getMessage()
- )
- ];
- }
- $hasData = count($data) > 0;
- return (object)[
- 'error' => $hasData,
- 'data' => $data,
- 'message' => $hasData ?
- 'OK' :
- 'No Data Found'
- ];
- }
- // index.phtml
- $posts = fetchPost('posts');
- if (!$posts->error) {
- echo sprintf('<div class="error">%s</div>', $posts->message);
- } else {
- array_map(static function ($item) {
- // Process item and render needed data
- }, $posts->data);
- }
Advertisement
Add Comment
Please, Sign In to add comment