Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create tree through recursive function

I have a table

id,name,parent_id,designation columns,

i want create tree through recursive function in php.

every parent_id is looking in id column and if user login then user can see own and all below records according parent_id.

like

A | B | c | D | E | F

if A user login then he can all(A,B,C,D,E,F) details.and if B login then see (B,c,D,E,F) and like all... if F login then he can see only own records.. Thanks for advance

like image 342
user1625518 Avatar asked Nov 13 '22 23:11

user1625518


1 Answers

create a function fetch_parent;

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's parent id
        fetch_parent($parent->parent_id); // here you go with your recursion
    }
    return;
}

Then just call the function with the record you want it's parents from:

$first_parent_id = 8;
fetch_parent($first_parent_id);

Notes:

  • the $parent var can also be an array, depending on the mysql result set
  • PLEASE PLEASE PLEASE check $parent_id in the query for mysql injection etc.
like image 165
giorgio Avatar answered Nov 15 '22 13:11

giorgio