Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
fussionlab opened this issue Feb 11, 2020 · 0 comments

Comments

@fussionlab
Copy link

fussionlab commented Feb 11, 2020

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..

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant