2

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.

4

1 回答 1

1

我不是 100% 确定我理解您的问题,但从您的代码中我猜您想知道给定论坛中有多少主题,包括该论坛可能拥有的任何子论坛。

我相信以下查询应该做到这一点:

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

请允许我对您的代码发表一些评论:

  • select *除非您真的需要所有数据,否则请避免使用。将您的查询限制在您需要的范围内。
  • 使用准备好的语句,而不是像您那样使用变量组合查询。如果您收到的 $formId 来自不安全的来源,这可能会构成安全线程。
  • 在循环内运行查询时要小心。你应该问问自己这是否真的有必要。在这种情况下,一个查询就足够了
  • 比较和搜索大型集合中的数据是数据库的设计目的。尽可能让他们完成工作,而不是获取大量数据并在 php.ini 中进行处理。
于 2016-05-07T22:00:27.837 回答