Forum Moderators: coopster

Message Too Old, No Replies

PHP-Mysql recursive while-loop help!

         

maxed

2:15 am on Oct 24, 2008 (gmt 0)

10+ Year Member



Okay i have a table, called types which has the structure example:

//id ¦ category ¦ roottyp\\
________________________
//1 ¦ toys ¦ root\\
//2 ¦ cars ¦ toys\\
//3 ¦ boats ¦ toys\\
//4 ¦ plastic ¦ cars\\
//5 ¦ metal ¦ cars\\
//6 ¦ candy ¦ root\\
________________________

Now by looking at that basically the table is support to sort categories, and they are sorted by the value of the roottyp column in each row.this value specifies the category that the row belongs to.

So in my site example.com according to the table the categories would be listed like:
Categories
+TOYS
-Cars
-plastic
-metal
-boats

+CANDY

Now the problem i face is to develop some sort of way to display all the categories and sort them under their root categories. I have used a collection of nested while and if statements to check and do this but its very bloated and is only able to do it for a few layers of categories...

--my code--
<strong>Example.com Category Structure</strong><br>';

$result = mysql_query("SELECT COUNT(*) FROM types WHERE roottyp = 'root' ")
or die(mysql_error());
$numberofresults = mysql_result($result, 0);
if($numberofresults !==0)
{
$result2 = mysql_query("SELECT * FROM types WHERE roottyp = 'root'")
or die(mysql_error());
while($row2 = mysql_fetch_array( $result2 ))
{
$regionz=$row2['category'];
echo'&nbsp;&nbsp;&nbsp;+'.$regionz.'<br />';
$resultx = mysql_query("SELECT COUNT(*) FROM types WHERE roottyp = '$regionz' ")
or die(mysql_error());
$numberofresults = mysql_result($resultx, 0);
if($numberofresults !==0)
{
$result3 = mysql_query("SELECT * FROM types WHERE roottyp = '$regionz'")
or die(mysql_error());
while($row3 = mysql_fetch_array( $result3 )) {
$regionz=$row3['category'];
echo'
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; - '.$regionz.'<br />';
}
}

}

}

--end--

there must be some way to recursively check and get the listing ussing a recursive function or something... but i just cant seem to figure out how....

maxed

10:17 am on Oct 24, 2008 (gmt 0)

10+ Year Member



Got it working thanks to the code from requinix:

function showlist($parent, $indent = "") {
$result = mysql_query("SELECT * FROM types WHERE roottyp = '" . mysql_real_escape_string($parent) . "'");
while ($line = mysql_fetch_array($result)) {
echo $indent, $line["category"], "<br>";
showlist($line["category"], "--" . $indent);
}
}

showlist("root");