Procedural Code: I get top layer categories and those underneath.

function selectCategory($parent_id = 0, $sub_mark = ''){

        global $con;
        $query = $con->query("SELECT * FROM `categories` WHERE `ParentID` = $parent_id ORDER BY `CategoryName` ASC");

        if($query->num_rows > 0){
            while($row = $query->fetch_assoc()){
                echo '<option value="' . $row['ID'] . '">' . $sub_mark.$row['CategoryName'] .'</option>';
                selectCategory($row['ID'], $sub_mark.'---');
            }
        }
    }

    echo selectCategory();

Place it inside an Object - call it var

$var = new var($db);
echo $var->();

And I only get the topic layer, it's not drilling into itself? why and how can I fix?

    public function selectCategory($parent_id = 0, $sub_mark = '', $html = ''){

        $query = $this->dbh->query("SELECT * FROM `categories` WHERE `ParentID` = $parent_id ORDER BY `CategoryName` ASC");

        if($query->num_rows > 0){
            while($row = $query->fetch_assoc()){
                $html .= "<option value=\"" . $row['ID'] . "\">" . $sub_mark.$row['CategoryName'] ."</option> \n";
                $this->selectCategory($row['ID'], $sub_mark.'- ', $html);
            }
        }

        return $html;
    } 

    Compare

                    $this->selectCategory($row['ID'], $sub_mark.'- ', $html);

    What happens to the HTML returned from this function call? In fact, the whole function gets confused about where $html comes from and where it's going.

        public function selectCategory($parent_id = 0, $sub_mark = ''){
            $html = '';
            $query = $this->dbh->query("SELECT * FROM `categories` WHERE `ParentID` = $parent_id ORDER BY `CategoryName` ASC");
    
            if($query->num_rows > 0){
                while($row = $query->fetch_assoc()){
                    $html .= "<option value=\"" . $row['ID'] . "\">" . $sub_mark.$row['CategoryName'] ."</option> \n";
                    $html .= $this->selectCategory($row['ID'], $sub_mark.'- ');
                }
            }
    
            return $html;
        } 

    ...though running multiple queries in a loop is a code smell.

      Write a Reply...