I want to have a dynamic menu that feeds from a table using php and mysql.
My table looks like this:
sec_id sec_name sec_group
1 section 1 g
$q = mysql_query("SELECT sec_id, sec_name, sec_group FROM tbl_user_sec ORDER BY sec_id");
// prepare data
$groups = Array();
while($w = mysql_fetch_assoc($q)) {
if(!isset($groups[$w['sec_group']])) $groups[$w['sec_group']] = Array();
$groups[$w['sec_group']][] = $w;
}
// display data
echo "<ul>";
foreach($groups as $group_name => $sections) {
echo '<li><a href="#">'.$group_name.'</a><ul>';
foreach($sections as $section) {
echo '<li><a href="#">'.$section['sec_name'].'</a>';
}
echo '</ul></li>';
}
echo "</ul>";
There is another solution if you don't care about sorting result by sec_id
$qry_secs="SELECT DISTINCT sec_group FROM tbl_user_sec ORDER BY sec_id ASC";
$result_secs = mysql_query($qry_secs);
echo '<ul>\n';
//echo values
while($row_secs = mysql_fetch_assoc($result_secs)) {
echo '<li><a href="#">'.$row_secs['sec_group'].'</a></li>\n';
echo '<ul>\n';
$newqry = "SELECT sec_name FROM tbl_user_sec WHERE `sec_group` = '" . mysql_real_escape_string($row_secs['sec_group'] . "'";
$result = mysql_query($newqry);
while($row = mysql_fetch_assoc($result) ) {
echo '<li><a href="#">' . $row['sec_name'] . '</li>\n';
echo '</ul>\n';
}
echo '</ul>\n';