tsvmitev tsvmitev - 4 months ago 8
MySQL Question

Category is not placed at the correct section

I have a problem while printing categories and sections (for a forum). So I have 2 tables : forum_section and forum_category -> the cat_id column from forum_section is linked with the

section
column from forum_category. Here's my query:

$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`");


And that's how I'm trying to print them:

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>';
}
}


That's my printCategories function:

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>';
}
}


So it does print them but not in the right place as you can see in this picture: enter image description here

Answer

printCategories needs to return the result, not echo it, so that the concatenation in the caller will put it into the DIV that it's echoing. Your code is echoing before it returns anything, so it gets printed before the caller concatenates the result and prints its 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;
}
Comments