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