mysql - PHP Categories with Sub Categories with sub sub -


i trying make category tree system display endless categories. database setup like:

id parent_id category_name

php code:

$cat_array = array(); $subcat_array = array();  if (mysqli_connect_errno())           {           echo "failed connect mysql: " . mysqli_connect_error();           }           $sql = mysqli_query($con, "select * `documents_category` isnull(parent_id)    "); while($row = mysqli_fetch_array($sql)) {      $cat_array[] = $row;   //echo $row['category_name']; }    // print_r($cat_array);    $sql2 = mysqli_query($con, "select * `documents_category`  parent_id not null ");  while($row2 = mysqli_fetch_array($sql2))  {      $subcat_array[] = $row2;    }     foreach ($cat_array $value)   {     echo "{$value['category_name']}<br/>";        foreach ($subcat_array $value2)      {             if($value2['parent_id'] == $value['id'])              {             echo "{$value2['category_name']}<br/>";             }       } 

}

the sub categories use parents id. can working upto 1 parent , sub after nothing shows up. have tried few different ways no luck. advice?

you need use recursion. use pdo tried make working example:

<?php $cat_array = array(); $subcat_array = array();  if (mysqli_connect_errno()) {     echo "failed connect mysql: " . mysqli_connect_error(); }           function getcategories($parent_id, $counter = 0) {      $sql = mysqli_query($con, "select * `documents_category` parent_id = " . (int)$parent_id);     while($row = mysqli_fetch_array($sql))     {         echo str_repeat("&nbsp;", $counter) . $row["id"] . " - " . $row["parent_id"] . " - " . $row["category_name"];         $sub_category = mysqli_query($con, "select * `documents_category` parent_id = " . (int)$row["id"]);         $counter++;         if(count($sub_category) > 0)             getcategories($row["id"], $counter);     } }  $parent_categories = getcategories(0); ?> 

as see, select "root" calling function. echo category. checks if has sub categories on current id, if found call function again parent_id of current row. if not found, go further... can use counter adding spaces or something....


Comments

Popular posts from this blog

ruby - Trying to change last to "x"s to 23 -

jquery - Clone last and append item to closest class -

css - Can I use the :after pseudo-element on an input field? -