Im trying to do a menu with with rows coming from the database, i have been reading here in stackoverflow about doing a recursive function to evaluate the parentId and Id and build the lower levels options, but with no luck. also tried to convert the sql answer to a multidimensional array with no luck...
Basically what i need is to build the set of list elements according to the parent, for example Dashboard.php is the parent of son.php
Here is my code:
function buildMenu($userType){
try{
$db = new db();
$conn = $db->conn();
$SQL_BUILD_MENU = "select usertypes.id as menuId,
menu.name as menuName, menu.link as menuLink,
usertype_menu.parent_id as
parent from usertypes inner join usertype_menu on usertypes.id = usertype_menu.usertype_id inner join
menu on usertype_menu.menu_id =
menu.id where usertypes.name='".$userType."'";
$conn->prepare($SQL_BUILD_MENU);
foreach($check = $conn->query($SQL_BUILD_MENU) as $row) {
echo "<ul>";
echo "<a href=".$row['menuLink']."><li>" . $row['menuName'] . "</li></a>";
echo "</ul>";
}
}
catch(Exception $e){
echo "Se ha presentado un error en buildMenu".$e;
}
}
}
+----+--------+-------------+-----------------+--------+
| id | menuId | menuName | menuLink | parent |
+----+--------+-------------+-----------------+--------+
| 1 | 1 | Dashboard | dashboard.php | 0 |
| 2 | 1 | Interaction | interaction.php | 0 |
| 3 | 1 | Son | Son.php | 1 |
+----+--------+-------------+-----------------+--------+
Thanks in advance.
Firstly, sanitise your query. Use a prepared statement and bind the paramater, don't string add.
Secondly, get all of the relevant data at once and build a data structure from it. Recursion is not the answer here.
Thirdly, unordered lists cannot have text as children. You need to encapsulate them in LI nodes.
<ul>
<li>Example 1</li>
<li>Example 2</li>
<li>
Example 3 with a child list
<ul>
<li>Example 3 Child 1</li>
</ul>
</li>
</ul>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.