How to call another function inside query result while loop and get results

I am creating a forum. It has sections. Each section has its own groups. I want to fetch all sections and their groups. But there is a problem with my code. plz check and tell me where the fault is. I want to create my forum exactly like this picture.
Image

Here is my code:-

    <?php

    // Database Configuration
    $_db['host'] = 'localhost';
    $_db['user'] = 'root';
    $_db['pass'] = '';
    $_db['name'] = 'ox';

    $db = new mysqli($_db['host'], $_db['user'], $_db['pass'], $_db['name']) or die('MySQL Error');

    class Forum {
        public function getForumSection() {
            // Run the query
            $result = $this->db->query("SELECT * FROM ow_forum_section");

            // Set the result into an array
            $sections = array();
            $groups = array();
            if($result->num_rows > 0) {
                while($row = $result->fetch_assoc()) {
                    $sections[] = $row;
                    $groups[] = $this->getForumGroup($row['id']);
                }
            }

            return $sections;
            return $groups;
        }
        public function getForumGroup( $sectionId ) {
            // Run the query
            $result = $this->db->query("SELECT * FROM ow_forum_group WHERE sectionId = '" . $sectionId . "'");

            // Set the result into an array
            $groups = array();
            if($result->num_rows > 0) {
                while($row = $result->fetch_assoc()) {
                    $groups[] = $row;
                }
            } 

            return $groups;
        }
    }

    $forum = new Forum();
    $forum->db = $db;
    $forumSection = $forum->getForumSection();

    foreach($forumSection as $section) {
            echo '<h2>'. $section['name'] . '</h2>';

            foreach($groups as $group) {
                echo $group['name'] . '<br>';
            }
    }
    ?>

When you say “there is a problem with my code”, it would be easier to spot if you could tell us how it doesn’t work the way you expect it to.

This bit doesn’t look right, at the end of the getForumSection() function definition:

            return $sections;
            return $groups;

From the documentation: “If called from within a function, the return statement immediately ends execution of the current function, and returns its argument as the value of the function call.” - so it will never hit the second return because the first has exited the function, and so your calling code won’t have access to $groups[]. You could return the two arrays as members of another array, or create an object to contain them, or no doubt several other ways.

Is that what the problem was?

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.