5

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

2
  • Is there one to one mapping between id and parent_id, in that case, you just get a link of ids, it won't be a tree. Commented Sep 5, 2012 at 9:04
  • yes,my table is mapped one by one between id and parent_id Commented Sep 5, 2012 at 9:10

1 Answer 1

1

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.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.