0

Ok Guys I am seriously stuck with this. Despite reading a dozen solutions I cannot get it straight..

Here is my MySql table..uid stands for user id and parentid stands for the parent where the user belongs.

    id  parentid  uid
    1   0         1
    2   1         2
    3   1         3
    4   2         4
    5   2         5
    6   3         6
    7   3         7

Now this is what I did.

            $con = mysql_connect("localhost","rtest","123456");
            if (!$con)
             {
              die('Could not connect: ' . mysql_error());
             }
            else
             {
              mysql_select_db("rtest", $con);
              $sql="SELECT * FROM parentchild WHERE parentid=1";
              $results=mysql_query($sql);
              while($row = mysql_fetch_array($results))
             {
                $levelone[] = $row;
             }
            }
            mysql_close($con);
            foreach ($levelone as &$value) {
              echo $value[uid]."<br>";
            }  

Here I have childs of the 1st element. I am unable to figure out how to take the second array and get the further values and store them in more arrays. I also need to access individual arrays later and I cannot call the entire table in one array for security reasons. My logic is really weak here.

Please help and advice. Thanx a ton in advance..

5
  • dipesharea.wordpress.com/2011/06/03/n-level-category Commented Mar 30, 2013 at 6:54
  • Maybe a duplicate of ? stackoverflow.com/questions/607052/… Commented Mar 30, 2013 at 7:01
  • 1
    What's the eventual data structure you're trying to create? Commented Mar 30, 2013 at 7:26
  • off topic, but it's worth pointing out that the mysql functions are deprecated; if at all possible, you should switch to using the mysqli or PDO libraries instead (preferably PDO). Commented Mar 30, 2013 at 8:02
  • @barmer i need to get a tree level structure but retail individual arrays for later use at each level. for example in the above code it gives out array for which the parent id is 1. i need that array then again iterate in that array and get 2 more arrays quering the database... Commented Mar 30, 2013 at 8:40

1 Answer 1

0

You can get the list of parentids by

SELECT DISTINCT parentid FROM parentchild

Now you can simply loop over this list and get the correspoding childs

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.