I Googled and found something that can work for me (http://wizardinternetsolutions.com/web-database-design/dynamic-multilevel-css-menu-php-mysql/). I plan to modify it a bit and tailor it to my needs, once I get it to work. -Ej. I want to use label
as Primary Key
rather than a random number.
However, I am getting an error: Warning: mysql_fetch_assoc() expects parameter 1 to be resource, boolean given in /home/content/81/10038181/html/_html/menu/menu-generator.php on line 23
The funny thing is, that when I run the query, it works fine.
Here is the table structure (SQL):
CREATE TABLE `menu` (
`id` int(11) NOT NULL auto_increment,
`label` varchar(50) NOT NULL default '',
`link` varchar(100) NOT NULL default '#',
`parent` int(11) NOT NULL default '0',
`sort` int(11) default NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=248 DEFAULT CHARSET=latin1;
PHP:
$dbc = new mysqli("localhost", "username", "password", "temp_database");
$dbn = "temp_database";
function display_children($parent, $level) {
$sql = "SELECT a.id, a.label, a.link, Deriv1.Count FROM `$dbn`.`menu` a LEFT OUTER JOIN (SELECT `parent`, COUNT(`parent`) AS Count FROM `".$dbn."`.`menu` GROUP BY parent) Deriv1 ON a.id = Deriv1.parent WHERE a.parent=" . $parent . " ORDER BY `sort`";
//echo $sql; //For testing purposes
$result = $dbc->query($sql);
echo "<ul>\n";
while ($row = $result->fetch_assoc() ) {
if ($row['Count'] > 0) {
echo "<li><a href='" . $row['link'] . "'>" . $row['label'] . "</a>";
display_children($row['id'], $level + 1);
echo "</li>";
}
elseif ($row['Count']==0) {
echo "<li><a href='" . $row['link'] . "'>" . $row['label'] . "</a></li>";
}
else;
}
echo "</ul>";
}
display_children(0, 1);