Romanovich095

Untitled

Mar 19th, 2021
1,225
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.18 KB | None | 0 0
  1. <?php
  2.  
  3. function fetchPost($table): object
  4. {
  5.     $data = [];
  6.  
  7.     try {
  8.         $this->db->query("SELECT id, title, body FROM $table ORDER BY id DESC ");
  9.         $rows = $this->db->fetchAll();
  10.  
  11.         // Map the data and apply changes
  12.         $data = array_map(static function ($row) {
  13.             return $row;
  14.         }, $rows);
  15.  
  16.         // Or directly apply rows to the data
  17.         $data = $this->db->fetchAll();
  18.     } catch (Exception $e) {
  19.         return (object)[
  20.             'error' => true,
  21.             'message' => sprintf(
  22.                 'Check %s class on %s method: %s',
  23.                 'SelectPosts',
  24.                 __METHOD__,
  25.                 $e->getMessage()
  26.             )
  27.         ];
  28.     }
  29.  
  30.     $hasData = count($data) > 0;
  31.  
  32.     return (object)[
  33.         'error' => $hasData,
  34.         'data' => $data,
  35.         'message' => $hasData ?
  36.             'OK' :
  37.             'No Data Found'
  38.     ];
  39. }
  40.  
  41. // index.phtml
  42. $posts = fetchPost('posts');
  43.  
  44. if (!$posts->error) {
  45.     echo sprintf('<div class="error">%s</div>', $posts->message);
  46. } else {
  47.     array_map(static function ($item) {
  48.         // Process item and render needed data
  49.     }, $posts->data);
  50. }
  51.  
  52.  
Advertisement
Add Comment
Please, Sign In to add comment