Oct
04

Simple PHP breadcrumb navigation

PHP,Tutorials          Trackback

I was working on one application this morning and I needed breadcrumb links on the top. First thought that came to me was: ‘recursion’. That’s scary word, for memory eating functions, but at the same time that is easiest way to create breadcrumbs navigation. All you have to do is to create MySQL table, with these fields: (category_id, parent_id, category_name)
Top categories must have parent_id set to 0. And here goes that simple recursive printbreadcrumb function:

function printbreadcrumb($category_id) {
	$sql = "SELECT category_id, parent_id, category_name
				FROM categories
				WHERE category_id=$category_id";
	$result	= mysql_query($sql) or die('something is wrong here');
	$row = mysql_fetch_array($result);
	if ($row['parent_id']) { // if this node has parent
		printbreadcrumb($row['parent_id']); // make recursive call to this function
	}
	echo $row['categories_name'].' > '; // print nodes one by one
	return;
}


You are calling this function like this: printbreadcrumb($category_id)

Some would say that this is slow script, because you’ll have same number of sql calls, as you have levels. What you can do is to change this function to work with arrays and to load that complete table in one array.


No Comments

Make A Comment

No comments yet.

Comments RSS Feed    TrackBack URL

Leave a comment

top