NOTE Please don't post answers about sql injection holes, I've already taken care about them: checking with in_array (if variable listed in column names array) and passing through real_escape.推荐答案假定当前页面ID在var $ current 中,并且$ db是一个开放的MySQLi DB连接:Assuming the current page id is in the var $current and that $db is an open MySQLi DB connection:// first get your current page's path back to root:// $stack will be a stack of menus to show$stack = array();// always expand current menu:$stack[] = $current;// now starting at $current, we go through the `menu` table adding each parent// menu id to the $stack until we get to 0:$i = $current;while ( $i > 0 ) { // get parent of $i $query = sprintf('SELECT `parent` FROM `menu` WHERE id=%d LIMIT 1', $i); $result = $db->query($query); if (!$result) { // do error handling here } $row = $result->fetch_assoc(); // save parent id into $i... $i = $row['parent']; // ...and push it onto $stack: $stack[] = $i;}/** * @param int $parent the parent ID of the menu to draw. * @param array $stack the stack of ids that need to be expanded * @param string $indent string for pretty-printing html * @param MySQLi $db Open db connection */function generateMenu($parent, $stack, $indent, $db){ // $next is the next menu id that needs expanding $next = array_pop($stack); $query = sprintf('SELECT `id`, `name` FROM `menu` WHERE `parent`=%d', $parent); $result = $db->query($query); if ( ! $result ) { // do error handling here } if ($result->num_rows > 0) { echo "\n$indent<ul>\n"; while($row = $result->fetch_object()){ echo "$indent <li>\n"; echo "$indent <a href=\"?page={$row->id}\">{$row->name}</a>\n"; //display this level's children, if it's the $next menu to need to be drawn: if ($row->id == $next) generateMenu($next, $stack, "$indent ", $db); echo "$indent </li>\n\n"; } echo "$indent</ul>\n"; } $result->free();}$first = array_pop($stack); // should always be 0generateMenu($first, $stack, '', $db); 这篇关于MySQL DB驱动的菜单生成器功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
11-02 07:27