0

I was only able to fetch a single ID with a value:

{"id":"2147483647","hyperlink":"0"}

My table:

id            hyperlink 
2147483647      0
2147483647      1

My read.php:

<?php 
  // Headers
  header('Access-Control-Allow-Origin: *');
  header('Content-Type: application/json');

  include_once '../../config/Database.php';
  include_once '../../models/Post.php';

  // Instantiate DB & connect
  $database = new Database();
  $db = $database->connect();

  // Instantiate blog post object
  $post = new Post($db);

  // Get ID
  $post->id = isset($_GET['id']) ? $_GET['id'] : die();

  // Get post
  $post->read_single();

  // Create array
  $post_arr = array(
    'id' => $post->id,
    'hyperlink' => $post->hyperlink
  );

  // Make JSON
  print_r(json_encode($post_arr));

My Post.php

<?php 
class Post {
  // DB stuff
  private $conn;
  private $table = 'views';

  // Post Properties
  public $id;
  public $hyperlink;

  // Constructor with DB
  public function __construct($db) {
    $this->conn = $db;
  }
  // Get Single Post
public function read_single() {
  // Create query


                              $query = "SELECT * FROM views p
                            LEFT JOIN
                              views c ON p.id = c.id 
                              WHERE 
                              p.id = ?";

  // Prepare statement
  $stmt = $this->conn->prepare($query);

  // Bind ID
  $stmt->bindParam(1, $this->id);

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

  $row = $stmt->fetch(PDO::FETCH_ASSOC);

  // Set properties
  $this->id = $row['id'];
  $this->hyperlink = $row['hyperlink'];
  
}
}

?>

I added comments to explain what the code does, My goal is whenever I send a GET request to this url /read.php?id=2147483647 I get a response back in JSON with the data:

[{"id":"2147483647","hyperlink":"0"}, {"id":"2147483647","hyperlink":"1"}] 

And if the same id had more than 2 different values it will be able to fetch all of it

  • `$post->id = conditional die()` is smelly code. Why are you `print_r()`ing the json string? Usually people just `echo`. `$querytest` should be commented out or removed entirely. – mickmackusa May 21 '22 at 09:21
  • Is the ID and other data all in one table? IF so what is with all the joins? Its very easy if all in one table! – JulesUK May 21 '22 at 09:24
  • @mickmackusa I prefer print_r(), is it bad should i change it echo – Snaxwill Beokay May 21 '22 at 09:24
  • Why join table `views` to itself? Your single row querying approach is not designed well for returning multiple rows -- you will be making a trip to the db for each id. This is very not good. There should be a `read_multiple()` method. Whatever is receiving your json should EXPECT multiple rows. – mickmackusa May 21 '22 at 09:26
  • @mickmackusa That's dumb my bad – Snaxwill Beokay May 21 '22 at 09:28
  • 1
    There's alot of unnecessary code i've to remove – Snaxwill Beokay May 21 '22 at 09:30

0 Answers0