Displaying a Breadcrumb Navigation for Multiple Sub Categories via PHP

While making an ecommerce store I ran into the issue of displaying a category breadcrumb. Usually this is easy as I always recommend keeping the numbers of categories and sub categories to a maximum of 1 level deep. E.g. Tshirts > Red tshirts. For this store, due to the sheer number of products the owner wanted to add up to seven category levels. While there are many tutorials on this floating about, they all seem tocus on displaying the whole tree – very useful for a sitemap page, but not a breadcrumb navigation. While it would have been possible to hard code several if statements into the category listing page, this seemed a bit messey and would cause problems if an eighth level was added.

For the breadcrumb naviagtion I needed a function to displaying the path to a given category ID, sometimes refered to as a single branch or node. I was using a simple parent child database table structure:

While the latter may seem fairly trival I really couldn’t get my head around the problem. After a bit of Googling, I found a function that was a good starting point so adapted it to fit my problem (the function is part of a categoru class):

function getCategoryTreeIDs($catID) {
		$row = DB::getInstance()->query("SELECT parent FROM categories WHERE ID = '$catID'")->fetch();
		$path = array();
		if (!$row['parent'] == '') {
			$path[] = $row['parent'];
			$path = array_merge($this->getCategoryTreeIDs($row['parent']), $path);
		}
		return $path;
	}

The function simply returns an array of category IDs. E.g 20, 28. So from the array I’d know that the tree would go as Home > Cat ID 20 > Cat ID 28.

Displaying the Breadcrumb Navigation

To display the actual breadcrumb I simply added the following method, that loops through the array of ID we just generated. The getNameLink method simply generates an SEO feindly website URL for the category, inside the <a> tag.

function showCatBreadCrumb($catID) {

		$array = $this->getCategoryTreeIDs($catID);

		$numItems = count($array);
		for ($i = 0; $i<=$numItems-1; $i++) {
			echo $this->getNameLink($array[$i]) . ' &raquo; ';
		}
	}

The result is a nicely formatted breadcrumb (to use our tshiorts example again):

Home &rquao; Clothes &rquao; tshirts &rquao; Mens &rquao; Red tshirts &rquao; Offensive &rquao;

A recursive function inside a loop, are you insane?

Some of you may have noticed that the function used to generate the category IDs is called recursively. This generally considered bad practice, for large data sets due to performance issues. However, for the current use this isn’t an issue. I know for a fact that client won’t be adding categories more than several levels deep, so performance really isn’t an issue in my eyes here. Maybe if we had hundreds of categories, but for several it’s really a non issue in my opinion.

getCategoryTreeIDs

Getting Multiple Array Form Values With PHP

php array code
PHP Arrays

Further to my article on using JQuery to dynamically append form elements, I have come across situations where multiple items should be appended to the form each time, as opposed to a single input in my article (I did this simplicity). For example, at work I’m currently working on an internal system whereby a user needs to add an unlimited amount of client contacts for a client. Pressing the ‘add contact’ link will append 3 fields – one for conatct name, contact telephone and contact email. Each of these fields are named exactly the same way as before (using square brackets at the end of the name E.g. ‘name[]’) and appended the same way using JQuery.

There are lots of articles floating about explaing how to add fields, but I’ve not yet seen anything explaining how to retreive multiple elements like this.

The only differnce arises when retreiving these multiple values from the PHP’s POST array. In the example I have appended 3 inputs, named cname[], cemail[] and ctel[]. The values of each can be retreived using a slightly enchanced for loop:

if (isset($_POST['cname'])) {
for ( $i=0;$i<count($_POST['cname']);$i++) {
$contactname = $_POST['cname'][$i];
$conatctemail = $_POST['cemail'][$i];
$contacttel = $_POST['ctel'][$i];
}
}

That’s really all there is to it and I’m finding that the latter comes in useful quit regularly in every day projects.

Simple Ajax Content Loading With JQuery

JQuery.com Logo
JQuery - JavaScript Framework

Occasionally it is useful to silently load content into an area on a webpage. For example, you may have a list of recent comments that you want to refresh every minute. Using a meta refresh is one option, but this would cause the whole page to refresh, which could annoy the user. The solution is Ajax, where I’ll reload the content silently without a single page refresh. Even writing the simplist of Ajax functions is quite painful and requires a fair few lines of code to get things done. To make things simpler we’ll use my favourite JavaScript Framework,  JQuery.

The plan is to have dynamic content loaded via Ajax and refresh every x seconds. We’ll also have a loading image to show the user something is actually happening behind the scenes, as having nothing while the content is loading could make the user leave. The latter is especially important when querying large sets of data, where a delay is possible. You can get your own loading images from the ajax loading image site.Now we have a plan, we’ll get right into it.

First course of action is to setup our basic html page. It’s nothing amazing, simply a centered divider with a seperate divider for the loading graphic. Here’s the code we’ll be using (for simplicity I’ve used the style tag for the css, as opposed to having a seperate css file:

Continue reading Simple Ajax Content Loading With JQuery

301 Redirects for SEO Using htaccess

301 Redirects Prevent 404 Errors
301 Redirects Prevent 404 Errors

Google treats www.website.com and website.com as two totally different websites. This is very bad for your (or even a client’s) website as it may lead to duplicate content and different pageranks to those sites.  This is how Google “canonicalizes” the url and is very bad from an SEO standpoint.

In essence, a web server could return totally different results for each of those pages. I have also encountered the situation where clients have set their preferred domain in Google webmaster tools, have given out the opposite version for SEM and wonder why they don’t see results :)You can easily check the above by using the “site:” operator in Google search. E.g. site:www.website.com and site:website.com

You can use “mod rewrite” rules as a powerful method for redirecting many URLs from one location to another.  This is a simple server level technique for handling redirects. The way people handle this canonicalization issue is purely a personal choice, although the below method can be altered for directing to the none www version of the url.

The .htaccess file is simply an ASCII file created with any normal text editor. You need to save the file as ‘.htaccess’ (no filename, .htaccess is the extension!). Open you newly created .htaccess file in your favoured text editor and add the following lines of code, replacing domain.com with your domain:

RewriteEngine On
RewriteCond %{HTTP_HOST} ^domain.com
RewriteRule (.*) http://www.domain.com/$1 [R=301,L]

Upload the .htaccess file to the root folder of your website and you’re done. All your traffic will be permanently redirected from a non-www version of your website to a www version of your website. To do the opposite (direct all traffic to the non www version use the below code in the .htaccess file):

RewriteEngine On
RewriteCond %{HTTP_HOST} ^www.domain.com
RewriteRule (.*) http://domain.com/$1 [R=301,L]