Introduction

Introduction – Introduction to DB_NestedSet

Overview

With this package, one can easily create trees with infinite depth inside a relational database. The package provides a way to

  • create/update/delete nodes
  • query nodes, trees and subtrees
  • copy (clone) nodes, trees and subtrees
  • move nodes, trees and subtrees
  • etc.

An example

Creates some root and subnodes

In this example, one rootnode and two subnodes are created, saved to the database and displayed.

<?php
require_once 'DB/NestedSet.php';
require_once 
'DB/NestedSet/Output.php';
require_once 
'HTML/Menu.php';
$DatabasePointer mysql_connect("localhost""user""pwd");
mysql_select_db("database"$DatabasePointer);
$dsn 'mysql://user:pwd@localhost/database';
// needed colums in table:
$params = array(
    
'id'        => 'id',
    
'parent_id' => 'rootid',
    
'left_id'   => 'l',
    
'right_id'  => 'r',
    
'order_num' => 'norder',
    
'level'     => 'level',
    
'name'      => 'name',
);
$nestedSet =& DB_NestedSet::factory('DB'$dsn$params);
$nestedSet->setAttr(array(
        
'node_table' => 'nested_set',
        
'lock_table' => 'nested_set_locks',
        
'secondarySort' => 'name',
    )
);
$parent $nestedSet->createRootNode(array('name' =>'root 1'), falsetrue);
$nestedSet->createSubNode($parent, array('name' => 'node 1.1'));
$nestedSet->createSubNode($parent, array('name' =>'node 1.2'));
$data $nestedSet->getAllNodes(true);

foreach (
$data as $id => $node) {
     
$data[$id]['url'] = 'index.php?nodeID=' $node['id'];
}

$params = array(
    
'structure' => $data,
    
'titleField' => 'name',
    
'urlField' => 'url');
$output =& DB_NestedSet_Output::factory($params'Menu');
$structure $output->returnStructure();
$menu = & new HTML_Menu($structure'sitemap');
$menu->forceCurrentUrl($currentUrl);
$menu->show();
?>