Aug 06 2017
Aug 06, 2017

Category tree from database using a PHP recursive function

Categorised in:

Good day, dear programmers! Today’s tutorial is about PHP recursive functions. We will use the recursion to get the category tree from the database and show it on a web page as in the example below:

According to elated.com, recursion occurs when something contains, or uses, a similar version of itself. That similar version then contains or uses another similar version of itself, and so on. Sometimes this process can go on forever, such as when you hold 2 mirrors directly opposite each other, creating an infinite series of reflections. More often, though, the number of repetitions, or "depth" of the recursion, is limited by some sort of end condition. 

Alright, to get started we need to have a database with at least a table. In my case the database’s name is tutorial and the table’s name is categories.

We need three columns in our table: id, name and parent. As you see in the example below I have four categories in my table.

Now we need to create a PHP file, in my case index.php, and paste there the fallowing code:

<?php
function CategoryTree(&$output=null, $parent=0, $indent=null){
	// conection to the database
	$db = new PDO("mysql:host=localhost;dbname=tutorial", 'root', '');
	// select the categories that have on the parent column the value from $parent
	$r = $db->prepare("SELECT id, name FROM categories WHERE parent=:parentid");
	$r->execute(array(
		'parentid' 	=> $parent
	));
	// show the categories one by one
	while($c = $r->fetch(PDO::FETCH_ASSOC)){
		$output .= '<option value=' . $c['id'] . '>' . $indent . $c['name'] . "</option>";
		if($c['id'] != $parent){
			// in case the current category's id is different that $parent
			// we call our function again with new parameters
			CategoryTree($output, $c['id'], $indent . "&nbsp;&nbsp;");
		}
	}
	// return the list of categories
	return $output;
}
// show the categories on the web page
echo "<select name='category'>
<option value='0'>Select a category</option>" . 
CategoryTree() . 
"</select>";
?>

 I left few comments in the PHP code so you can understand it better. This is just an example of recursion. You can copy and modify it however you want. I made a video tutorial where I explain step by step how this function runs. You can find it right here.

 Don’t forget to subscribe for my YouTube channel for more tutorials. ;)