Forum Moderators: coopster
I am working in a project, and every thing was going will, until I stoked in a problem with a recursive method.
The idea was to iterate through a table and echo's the results as a tree like this:
Root_folder
Sub_root_1
Sub_root_2
Sub_root_3
Root_folder
Sub_root_1
Sub_sub_1
Sub_sub_2
The condition is if there is a sub folder the parent folder will be colored
I tried to make a recursive method but this is my result.
test1test1test1test1
catogery1
Category
Category
Category
catogerytest2
Category
you can see that it dos not add test1 to the biginig of the string
here is my code
function get_categories_send($parent_id,$level)
{
$sql_command="SELECT * FROM categories WHERE categ_parent=".$parent_id;
$result=mysql_query($sql_command);
while($fetch_em=mysql_fetch_array($result))
{
global $main_contents;
$id = $fetch_em['id'];
$name = $fetch_em['categ_name'];
$level++;
$main_contents =$main_contents."<br>".$name.$level;
//************************************to check for sub categories
$sql_command_2="SELECT * FROM categories WHERE categ_parent=".$id;
$result_2=mysql_query($sql_command_2);
if(mysql_num_rows($result_2)>0)
{
$main_contents="test1".$main_contents."test2";
}
//************************************end of sub categories chkeck
get_categories_send($id,$level--);
}
return $main_contents;
}
CREATE TABLE `categories` (
`id` int(11) NOT NULL auto_increment,
`categ_name` varchar(255) character set utf8 collate utf8_bin NOT NULL,
`categ_show` varchar(3) default '0',
`categ_parent` int(11) NOT NULL default '0',
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=61;
But I finally discovered my mistake and here is the finale function.
I know there is a butter solution but this is what I could do,and hope some one will find it useful.
function get_categories_send($parent_id,$level)
{
$sql_command="SELECT * FROM categories WHERE categ_parent=".$parent_id;
$result=mysql_query($sql_command);
while($fetch_em=mysql_fetch_array($result))
{
global $main_contents ;
$id = $fetch_em['id'];
$name = $fetch_em['categ_name'];
$level++;
//************************************to check for sub categories
$sql_command_2="SELECT * FROM categories WHERE categ_parent=".$id;
$result_2=mysql_query($sql_command_2);
if(mysql_num_rows($result_2)>0)
{
$main_contents=$main_contents."<optgroup label='".str_repeat(". ",$level++).$name."'></optgroup>";
}
else
{
$main_contents =$main_contents."<option>".$name.$level."</option>" ;
}
//************************************end of sub categories chkeck
get_categories_send($id,$level--);
}
return $main_contents ;
}