Create a tree through a recursive function

I have a table

id,name,parent_id,designation,

I want to create a tree through a recursive function in php.

each parent_idis in the column id, and if the user enters a login, then the user can see their own and all below entries in accordance with parent_id.

like

a | In | with | D | E | F

if the user login, then it can do everything (A, B, C, D, E, F) details.and if B login, then look (B, c, D, E, F) and like everyone else ... if F then he can only see his own records .. Thanks for the promotion

+5
source share
1 answer

create a fetch_parent function;

function fetch_parent($parent_id) {
    $query = 'SELECT * FROM `my_table` WHERE `parent_id`='. $parent_id;
    // use your own sql class/function whatever to retrieve the record and store it in variable $parent
    if($parent->parent_id !== null) { // asuming a 'root' record will have null as it parent id
        fetch_parent($parent->parent_id); // here you go with your recursion
    }
    return;
}

Then just call the function with the entry you want from it:

$first_parent_id = 8;
fetch_parent($first_parent_id);

Notes:

  • $parent var , mysql
  • , , , $parent_id mysql ..
+1

All Articles