-1

I'm fairly new with PHP and with MySQL/Wampserver/MVC model, as i'm still learning it. In a project i'm working on, i have a database containing multiple tables ( users, posts, commentary ). I've worked out how to 1)register a new post inside the db upon submitting a form, and on an homepage, fetch all the posts to show them in a list. Such has been done through the following code :

 public function getAllPosts()
    {
        $query = "SELECT * FROM posts ORDER BY timestamp(date) desc LIMIT 5";
        $request = $this->db->prepare($query);
        $request->execute();
        $allPost = $request->fetchAll(PDO::FETCH_ASSOC);
        var_dump($allPost);

        return $allPost ? $allPost : [];
    }

$allPost here is returned as an array, containing multiple infos Since this array contains the IDs of every post, my idea to select a specific ID from a specific post is to fetch the ID existing in the array generated to make the list of post, and pass it to the address with the POST method.

Is this a convoluted thing to do ? If so, what would you suggest i do instead ?

The things i tried so far : Create a new public function that grabs the ID with a new query from the database ( "SELECT id FROM tablename WHERE id=?") but this did not work, and simply returned " boolean false " on var_dump

    public function getOnePostById()
    {
        $query = "SELECT id FROM posts WHERE id=?";
        $request = $this->db->prepare($query);
        $request->execute();
        $singlePost = $request->fetch(PDO::FETCH_ASSOC);
        var_dump($singlePost);
    }

I then tried to pass to getOnePostById the resulting array from the previous function while this seems to be accepted by my code, in my controller afterwards, the array $allPost was flagged as an undefined variable

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
Alexis P.
  • 23
  • 2
  • I don't get your question. What do you even mean, "How would i go about grabbing the ID of a post"? Did you get your $allPost array for any purpose? Did you try to use any information from it? What's the problem with id then? This column is no different from any other column in the post data. – Your Common Sense Dec 24 '22 at 07:38
  • 1
    `SELECT id FROM tablename WHERE id=?` doesn't make much sense. Why would you select from database exactly the same id that you have already? What's the logic here? – Your Common Sense Dec 24 '22 at 07:44

1 Answers1

-1

You have to provide a value for a placeholder in the query, either by using bindParam or bindValue method of PDOStatement or adding it as array parameter to execute()

    public function getAllPosts(): array
    {
        $query = "SELECT * FROM posts ORDER BY timestamp(date) desc LIMIT 5";
        $request = $this->db->query($query);
        return $request->fetchAll(PDO::FETCH_ASSOC);
    }

    // if your Post ID is not a number, use string $id
    public function getOnePostById(int $id): ?array
    {
        $query = "SELECT * FROM posts WHERE id = ?";
    
        $request = $this->db->prepare($query);
        $request->execute([$id]);
        return $request->fetch(PDO::FETCH_ASSOC);
    }

    // Here you can just check post existence by given id
    // if your Post ID is not a number, use string $id
    public function isPostExists(int $id): bool
    {
        $query = "SELECT 1 AS exist FROM posts WHERE id = :id";
    
        $request = $this->db->prepare($query);
        // if your Post ID is not a number, use PDO::PARAM_STR
        $request->bindParam('id', $id, PDO::PARAM_INT);
    
        $request->execute();
        
        // FETCH_OBJ example
        return (bool)$request->fetch(PDO::FETCH_OBJ);
    }

P.S. FETCH_ASSOC is bad practice (because it's just an array, it can be a list of entries, or it can be a single entry). PDO::FETCH_OBJ should be preferred.
See more about PDO fetch modes and how to set default fetch mode (for entire PDO instance, not just PDOStatement) and many other settings here.

UPD: And also $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); is good practice, your PDO instance will throw exceptions instead of silent failures.

See difference between bindParam and bindValue - here

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
Dmitry K.
  • 3,065
  • 2
  • 21
  • 32
  • You probably confused Stack Overflow with https://codereview.stackexchange.com/. The OP didn't ask to rewrite his code. He asked a certain question that hasn't been answered in your post. The rewrite is also questionable. OP's approach to prepared statements is all right. Some suggestions are questionable as well. fetch() cannot return a list of entries, it will be always a single entry. – Your Common Sense Dec 24 '22 at 07:32
  • @YourCommonSense > You probably confused Stack Overflow with codereview.stackexchange.com. Perhaps so > OP's approach to prepared statements is all right Not correct, see OP's getOnePostById method, query is `SELECT id FROM posts WHERE id=?`, but there is no bindings > fetch() cannot return a list of entries, it will be always a single entry. That's correct, but I'm talking about that case: `getAllPosts()` - will return an array of arrays and `getOnePostById()` will return an array – Dmitry K. Dec 24 '22 at 07:45
  • OP's getOnePostById just makes no sense AT ALL, with prepared statements or without. – Your Common Sense Dec 24 '22 at 07:48
  • getAllPosts() will return an array of arrays and getOnePostById() will return an array - so what's the problem then? FETCH_ASSOC by no means is a "bad" practice but just a personal preference. – Your Common Sense Dec 24 '22 at 07:51
  • @YourCommonSense it's bad practice because you don't even know if you're working with a collection of rows or a row itself – Dmitry K. Dec 24 '22 at 08:04
  • Now again. getAllPosts() returns a collection of rows. I DO know it's a collection of rows. getOnePostById() will returns a row itself. I DO know it's a single row. I have not a single problem reading my code and understanding what does it do. In case you are talking of some type hinting, THEN using just a generic stdObject is not much help and your getOnePostById is better to return a specific Post instance. In this case it will indeed take the advantage of type hinting – Your Common Sense Dec 24 '22 at 08:10
  • @YourCommonSense you're right – Dmitry K. Dec 24 '22 at 08:18