Tuesday 15 April 2014

Tree Structure Menu with php Using Recursive

<code>
CREATE TABLE IF NOT EXISTS `menu` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `id_parent` int(11) NOT NULL DEFAULT '0',
  `link` varchar(255) NOT NULL,
  `order` int(11) NOT NULL DEFAULT '0',
  `title` varchar(255) CHARACTER SET utf8 COLLATE utf8_polish_ci NOT NULL DEFAULT '',
  `level` tinyint(4) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=24 ;



INSERT INTO `menu` (`id`, `id_parent`, `link`, `order`, `title`, `level`) VALUES
(12, 0, '', 0, 'Office Furniture', 0),
(13, 12, '', 0, 'Chairs', 0),
(14, 12, '', 0, 'Work Tables', 0),
(15, 12, '', 0, 'Workstations', 0),
(16, 12, '', 0, 'Storage', 0),
(17, 12, '', 0, 'Conference Tables', 0),
(18, 13, '', 0, 'with spagh', 0),
(19, 13, '', 0, 'without spagh', 0),
(20, 18, '#', 0, 'Triangle', 0),
(21, 18, '#', 0, 'Sqare', 0),
(22, 19, '#', 0, 'Simple', 0),
(23, 19, '#', 0, 'Complex', 0);




</code>

PHP Code for that example


<code>



<?php

        $db = new PDO('mysql:dbname=test13', 'root', '',
    array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));


function createsubmenu( $item )
{
    global $db;
// prepare a query to get subitems of the current $item (those with parent = $item)
    $subsel = $db->prepare('SELECT id, link, title, level  FROM menu WHERE id_parent = :parent ORDER BY `order`');
// run the query
    $subsel->execute(array('parent' => $item));
    $text = '';
// fetch one row at a time, when no more rows are available $i
// will be false and while ends
    while( ($i = $subsel->fetch(PDO::FETCH_OBJ)) !== false ) {
// generate code for the current $item
// will recursively call createsubmenu to add possibly existing subitems
        $text .= '<li class="menucolor' . ($i->level - 1) . '">'
            .'<a href="' . htmlspecialchars($i->link) . '">' . htmlspecialchars($i->title) . '</a>'
            . createsubmenu($i->id) . '</li>';
    }
// there were no items for the current call
    if( $text == '' )
        return '';
// items were found, wrap them in an unordered list
    return '<ul id="red" class="treeview-red">' . $text . '</ul>';
}

echo createsubmenu(0);
?>
</code>


I have recently modified code So, that you get the same result with minimum query from the database.





OUT LIKE THIS


No comments:

Post a Comment