Getting Child

By admin at 20 November, 2008, 12:26 pm

During my project, I need a code to show the items and it’s corresponding child, of certain category. So, finally I come up with this code. If you are also in sort of such problem and wondering how to get the child of its parent (tree),then this piece of code may acts as your helper.
This is very simple example of showing in tree structure but hopefully a good one to use.

[Source code]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
 
<?php
 
 
function display_children($parent, $level) {
 
	//db connection
        $dbcon = mysql_connect("localhost","root","") or die("Cant connect to db");
	$select_db = mysql_select_db("db_name",$dbcon);
 
	if(!$select_db)
	{
	   die("Cannot access database:".mysql_error());	
	}
 
	// retrieve all children of $parent
	$query = "SELECT * FROM table_name WHERE parent_id='$parent'";
	$result = mysql_query($query,$dbcon);
 
	// display each child
	while ($row = mysql_fetch_array($result)) {
		// indent and display the title of this child
		echo str_repeat('->',$level).$row['child_name']."\n<br>";
		display_children($row[child_id], $level+1);
	}
}//end of function
?>

Spread the Words!




No comments yet.

Sorry, the comment form is closed at this time.