Search code examples
phpbreadcrumbs

Creating a "guide bar" like this, above a web page by php+mysql?


I want to create a "guide bar" (I don't know its right name). I've got a table called cat that has the following data:

catid        catname         parentid
1            news            null
2            sport           1
3            health          1
4            tennis          2
5            football        2
6            soccer          5

My page receives: $catid=6, and I want to create:

news>sport>football>soccer

Solution

  • First get your data from database and build an array

    $q = mysql_query("SELECT catid, catname, parentid FROM cat");
    $pages = array();
    while($r = mysql_fetch_assoc($q)) {
        $pages[$r['catid']] = array('catname' => $r['catname'], 'parentid' => $r['parentid']);
    }
    

    Use a recursive function to build the breadcrumbs:

    function build_breadcrumbs($pages, $catid) {
        if(is_null($catid) || empty($catid)) return;
        return build_breadcrumbs($pages, $pages[$catid]['parentid']).$pages[$catid]['catname'].' > ';
    }
    

    The function returns the parent's breadcrumbs + the current breadcrumb. Use the function like this:

    $catid = 6;
    $breadcrumbs = trim(build_breadcrumbs($pages, $catid), ' >');
    echo $breadcrumbs;
    

    Or, if you like arrays more, you can create a function like this:

    function build_breadcrumbs($pages, $catid) {
        if(is_null($catid) || empty($catid)) return array();
        return array_merge(build_breadcrumbs($pages, $pages[$catid]['parent']), array($pages[$catid]['name']));
    }
    

    and use it with implode:

    $catid = 6;
    $breadcrumbs = implode(' > ', build_breadcrumbs($pages, $catid));
    echo $breadcrumbs;
    

    That gives you the option to define the separator outside the function. Hope that helps.