Recursive tree traversal using mysql via PHP

I am creating a questionnaire for a client that requires questions to be organized in three levels. I successfully created the UI however I have been trying for the last 3 hours to retrieve data from the database so that everything loads in the right place. The database is organized this way by the client, so I do not control it:

id    description    parentId    
1      Level 1        0           
2      Level 2        0           
3      Level 1a       1   
4      Level 1b       1 
5      Level 1a1      3      

I found a similar question for mine on the site, but when I tried to solve it, I got the following on repetition endlessly:

the code:

function makeList($par_id = 0) {
    //your sql code here
    $result = mysql_query("SELECT * FROM pB_test WHERE parentId = $par_id");
    $pages = mysql_fetch_array( $result );

    if (count($pages)) {
        echo '<ul>';
        foreach ($pages as $page) {
            echo '<li>', $page['description'];
                makeList($page['parentId']);
                echo '</li>';
        }
        echo '</ul>';
    }
}

makeList();

Conclusion:

1
3
5
5
l
l
3
5
5
l
l
3
5
5
l
l
3
5
5
l
l

Does anyone know how to fix this and what is the problem? Greetings

+5
source share
2 answers

Do it recursively:

function printChildQuestions($parentid) {
  $sql="SELECT * FROM pB_test WHERE parentID=$parentid";
  $result=mysql_query($sql);
  $i=0;
  while (true) {
    $row=mysql_fetch_array($result);
    if (!$row) break;
    if ($i==0) echo "<ul>";
    $i=1;
    echo '<li>'.$row['id'].'&nbsp;'.$row['description'].'&nbsp;'.$row['parentId'].'</li>';
    printChildQuestions($row['id']);
  }
  if ($i>0) echo '</ul>';
}

printChildQuestions(0);
+6
source

It is not good to call a mysql server and fetch result every time

, 100 ? 200 +

:

$result = mysql_query("SELECT * FROM test");
$arrs = array();

while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
    $arrs[] = $row;
}

function build_tree($arrs, $parent_id=0, $level=0) {
    foreach ($arrs as $arr) {
        if ($arr['parent_id'] == $parent_id) {
            echo str_repeat("-", $level)." ".$arr['name']."<br />";
            build_tree($arrs, $arr['id'], $level+1);
        }
    }
}

build_tree($arrs);

  id    name    parent_id
+8

All Articles