0

I have the following code to create category and subcategories from a database

function displayChild($parent)
{
    include 'connect.php';
    $parentid=$parent;
    $catSql='select* from categories where parentid='.$parentid.'';
    $result=$con->query($catSql);
    echo '<div><ul class='.'ul'.$parentid.'>';
    while ($rows=$result->fetch_assoc())
    {
        echo '<li><a href="#">'.mb_strtoupper($rows['catName']).'</a></li>';
        displayChild($rows['catId']);
    }
    echo '</ul></div>';
}
displayChild('0');

The CSS bits should be as follows

@charset "utf-8";
.ul0{}
.ul1{}
.ul2{}
.
.
.
.uln{}

since the first tag appears outside the while loop it forms a really weird list when i reference it.putting it inside the while() loop is not an option either. please help

Gurtej Singh
  • 3,244
  • 1
  • 14
  • 27
kimarry88
  • 1
  • 2
  • Your code may be vulnerable to SQL injection attacks. You should use [mysqli](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) or [PDO](http://php.net/manual/en/pdo.prepared-statements.php) prepared statements as described in [this post](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php). – Alex Howansky Apr 11 '17 at 14:43

1 Answers1

0

I'm not exactly sure what you mean by " it forms a really weird list when i reference it." However, it sounds like maybe you are getting odd html. If that's the case, you get better results if you put the nested function call inside the li:

function displayChild($parent){
  include 'connect.php';
  $parentid=$parent;
  $catSql='select* from categories where parentid='.$parentid.'';
  $result=$con->query($catSql);
  echo '<div><ul class='.'ul'.$parentid.'>';

  while ($rows=$result->fetch_assoc()){
    echo '<li><a href="#">'.mb_strtoupper($rows['catName']).'</a>';
    displayChild($rows['catId']); // note this is now inside the list item
    echo '</li>';
  }
  echo '</ul></div>';
}
vlasits
  • 2,215
  • 1
  • 15
  • 27