类别未放置在正确的部分

时间:2016-08-02 21:13:24

标签: php mysql

我在打印类别和部分时遇到问题(对于论坛)。所以我有2个表:forum_section和forum_category - >来自forum_section的cat_id列与forum_category中的section列相关联。这是我的疑问:

$forum = $con->query("SELECT a.*, b.*
    FROM `forum_section` a
    INNER JOIN `forum_category` b ON a.`cat_id` = b.`section` GROUP BY a.`cat_name` ORDER BY a.`cat_id`");

这就是我试图打印它们的方式:

while($row = mysqli_fetch_object($forum)) {
        echo '<div id="section">
              <div class="section-head"><h3 class="yellow_text">'.$row->cat_name.'</h3></div>
                '.printCategories($row->cat_id).'
            </div>';
    }
}

这是我的printCategories功能:

function printCategories($id) {
    global $con;

    $categories = $con->query("SELECT * FROM `forum_category` WHERE `section`='$id'");

    while($row = mysqli_fetch_object($categories)) {
        echo '<div class="cat">
                <div class="cat-title">
                  <img src="styles/default/images/icons/'.$row->icon.'.png" alt="Icon">
                  <span>'.$row->name.'</span>
                </div>
                <div class="cat-topics">
                    asd
                </div>
                <div class="cat-posts">
                    asd
                </div>
                <div class="cat-lasttopic">
                    last topic name goes here
                </div>
              </div>';
    }
}

所以它会打印出来但不在正确的位置,如下图所示:enter image description here

1 个答案:

答案 0 :(得分:1)

printCategories需要return结果,而不是echo,因此调用者中的串联会将其放入DIV echo ING。您的代码在返回任何内容之前都会回显,因此在调用者连接结果并打印其DIV之前会打印它。

function printCategories($id) {
    global $con;

    $categories = $con->query("SELECT * FROM `forum_category` WHERE `section`='$id'");
    $result = '';
    while($row = mysqli_fetch_object($categories)) {
        $result += '<div class="cat">
                <div class="cat-title">
                  <img src="styles/default/images/icons/'.$row->icon.'.png" alt="Icon">
                  <span>'.$row->name.'</span>
                </div>
                <div class="cat-topics">
                    asd
                </div>
                <div class="cat-posts">
                    asd
                </div>
                <div class="cat-lasttopic">
                    last topic name goes here
                </div>
              </div>';
    }
    return $result;
}