title: Building breadcrumbs for unlimited category depth - PHP + SQL
body: <p>I'd like to be able to build the breadcrumbs for a content page, however the categories a piece of content is in can have unlimited depth, so i'm not sure how to go about it without getting each category one by one and then getting its parent etc. It seems like it could be a simpler way but I can't figure it out.</p>
  
  <p>I have an articles table</p>
  
  <pre><code>article_id
  article_name
  article_cat_id
  </code></pre>
  
  <p>I also have a categories table</p>
  
  <pre><code>cat_id
  cat_name
  cat_parent
  </code></pre>
  
  <p>Cat parent is the id of another category of which a category is a child.</p>
  
  <p>Imagine an article which is 5 categories deep, as far as I can tell i'd have to build the breadcrumbs something like this (example code obviously inputs should be escaped etc)</p>
  
  <pre><code>&lt;?php
  $breadcrumbs = array(
      'Category 5',
      'Content Item'
  );
  $cat_parent = 4;
  
  while($cat_parent != 0) {
      $query = mysql_query('SELECT * FROM categories WHERE cat_id = '.$cat_parent);
      $result = mysql_fetch_array($query, MYSQL_ASSOC);
      array_unshift($breadcrumbs, $result['cat_name']);
      $cat_parent = $result['cat_parent'];
  }
  ?&gt;
  </code></pre>
  
  <p>This would then give me</p>
  
  <pre><code>array(
  'Category 1',
  'Category 2',
  'Category 3',
  'Category 4',
  'Category 5',
  'Content Item'
  )
  </code></pre>
  
  <p>Which I can use for my breadcrumbs, however its taken me 5 queries to do it, which isn't really preferable.</p>
  
  <p>Can anyone suggest any better solutions?</p>