Reputation: 50
I'm trying to get all the topics from my forum and the sub-forums in it. However, for some reason, my code doesn't work properly. It doesn't give me any errors, but it shows wrong information. I am using the medoo. Here is my function:
public function getForumTopicsCount($forumId)
{
$getForumTopicsCount = $this->db->count('forum_topics', [
"topic_forum" => $forumId
]);
$subForums = $this->db->query("SELECT * FROM `forums` WHERE forum_subforum = $forumId")->fetchAll();
$c = 0;
foreach($subForums as $subForum) {
$subForumTopics = $this->db->query("SELECT * FROM `forum_posts`")->fetchAll();
foreach($subForumTopics as $topic) {
if ($subForum['forum_id'] == $topic['topic_forum']) {
$c++;
}
}
}
return $getForumTopicsCount + $c;
}
So in my database I have a table forums and there I have a column forum_subforum which is an integer and its value is the id of their head forum. I also have a forum_topics table which consists of all the topics in my whole forum, where i have a column named topic_forum which is also and integer and is the id of the forum which the topic belongs to.
Thank you for the help. It is highly appreciated.
Upvotes: 2
Views: 120
Reputation: 14310
I'm not 100% sure I understand your question, but from your code I guess you want to know how many topics there are in a given forum, including any sub forums that forum may have.
I believe the following query should do exactly that:
select count(*) from forum_topics
right join forums on forum_topics.topics_forum = forums.id
where forums.forum_id = :id or forums.forum_subforum = :id
Allow me to give you a few remarks on your code:
select *
unless you really need all the data. Limit your queries to what you need.Upvotes: 1