Skip to content

Why can't we fetch all data from post and return it to read.php? To reduce the code  #9

@fussionlab

Description

@fussionlab

Why can't we get fetch all data form table and just return that data, then in while reading data just pass that data into to json_encode something like this?
In models/Post.php

        // Get Posts
    public function read() {
      // Create query
      $query = 'SELECT c.name as category_name, p.id, p.category_id, p.title, p.body, p.author, p.created_at
                                FROM ' . $this->table . ' p
                                LEFT JOIN
                                  categories c ON p.category_id = c.id
                                ORDER BY
                                  p.created_at DESC';
      
      // Prepare statement
      $stmt = $this->conn->prepare($query);

      // Execute query
      $stmt->execute();

      return $stmt;
    }

Above code to

// Get Posts
    public function read() {
      // Create query
      $query = 'SELECT c.name as category_name, p.id, p.category_id, p.title, p.body, p.author, p.created_at
                                FROM ' . $this->table . ' p
                                LEFT JOIN
                                  categories c ON p.category_id = c.id
                                ORDER BY
                                  p.created_at DESC';
      
      // Prepare statement
      $stmt = $this->conn->prepare($query);

      // Execute query
      $stmt->execute();

      return  $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

Then in api/post/read.php

$stmt = $post->read();
$count = Count($stmt);
if($count>0){
    echo json_encode( $stmt);
}
else {
    echo json_encode(
      array('message' => 'No Posts Found')
    );
}

So that we can cut short the coding right..

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions