Jump to content


Photo

Infinite query


  • Please log in to reply
3 replies to this topic

#1 Desdinova

Desdinova
  • Members
  • PipPipPip
  • Advanced Member
  • 41 posts

Posted 02 April 2006 - 02:02 PM

Ok well this is the case.

I have a mysql database, with a table Menuitems: ID, Name, LinkedID.

The idea is this,
a menuitem gets an incremented ID, a name, and a linkedID. The linkedID shows which ID is the menu's parent. Now I want the childs to go infinitely deep, meaning I need some sort of query loop.

Brief example:
[!--quoteo--][div class=\'quotetop\']QUOTE[/div][div class=\'quotemain\'][!--quotec--]

ID----Name--------LinkedID
1-----MenuA----------0------
2-----MenuB----------0------
3-----SubmenuA-----1------
4-----SubmenuAA----3-----
[/quote]

This would produce:
[!--quoteo--][div class=\'quotetop\']QUOTE[/div][div class=\'quotemain\'][!--quotec--]
MenuA
--SubmenuA
----SubmenuAA
MenuB
[/quote]

As you can see, if LinkedID = 0, the menu is not a child, else it is.
So everytime LinkedID != 0, a query must be called.

How can I loop this?

#2 emehrkay

emehrkay
  • Staff Alumni
  • Advanced Member
  • 1,214 posts

Posted 02 April 2006 - 02:21 PM

you should be able to set this up with a few lines of code

$query = "SELECT * FROM table WHERE linkId = 0";
$result = mysql_query($query) or die ("COULD NOT RUN QUERY <br />".mysql_error());
while($row = mysql_fetch_array($result)){
//print something
$query = "SELECT * FROM table WHERE linkId = ". $row['id']. "";
$result = mysql_query($query) or die ("COULD NOT RUN QUERY <br />".mysql_error());
//print somehting
}

there should be a way to do this without having to run so many queries, like putting all of the data in an array and looping through that array placing zero items at zero and their children under that

#3 Desdinova

Desdinova
  • Members
  • PipPipPip
  • Advanced Member
  • 41 posts

Posted 02 April 2006 - 02:41 PM

Yes I had it like that. But the problem with this is, that it only gets as much childmenu's as the amount of queries I put in it, thus not making it infinitely deep.

#4 kenrbnsn

kenrbnsn
  • Staff Alumni
  • Advanced Member
  • 8,235 posts
  • LocationHillsborough, NJ, USA

Posted 02 April 2006 - 04:15 PM

You need to put the second query in a loop. Something like:
<?php
$query = "SELECT * FROM table WHERE linkId = 0";
$result = mysql_query($query) or die ("COULD NOT RUN QUERY <br />".mysql_error());
while($row = mysql_fetch_assoc($result)){
//print something
    $linkId = $row['id'];
    while ($linkId != 0) {
        $subquery = "SELECT * FROM table WHERE linkId = ". $row['id']. "";
        $subresult = mysql_query($subquery) or die ("COULD NOT RUN QUERY <br />".mysql_error());
        $subrow = mysql_fetch_assoc($subresult);
        // do something with the results
        $linkId = $subrow['id'];
    }
}?>

Ken




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users