title: Multilevel menu from database records
body: <p>I need some help with PHP. I have a multilevel css menu that works fine, but now I want to generate according to the records from a database.</p>
  
  <p><strong>The menu Code:</strong></p>
  
  <pre><code>&lt;div id="page-wrap"&gt;
      &lt;ul class="dropdown"&gt;
          &lt;li&gt;&lt;a href="#"&gt;Link 1&lt;/a&gt; &lt;/li&gt;
          &lt;li&gt;&lt;a href="#"&gt;Link 2&lt;/a&gt; &lt;/li&gt;
          &lt;li&gt;&lt;a href="#"&gt;Link 3&lt;/a&gt; &lt;/li&gt;
          &lt;li&gt;&lt;a href="#"&gt;Link 4&lt;/a&gt;
          &lt;ul class="sub_menu"&gt;
              &lt;li&gt;&lt;a href="#"&gt;Link 4 - 1&lt;/a&gt;&lt;/li&gt;
              &lt;li&gt;&lt;a href="#"&gt;Link 4 - 2&lt;/a&gt;&lt;/li&gt;
              &lt;li&gt;&lt;a href="#"&gt;Link 4 - 3&lt;/a&gt;&lt;/li&gt;
          &lt;/ul&gt;
          &lt;/li&gt;
          &lt;li&gt;&lt;a href="#"&gt;Link 5&lt;/a&gt;&lt;/li&gt;
          &lt;li&gt;&lt;a href="#"&gt;Link 6&lt;/a&gt; &lt;/li&gt;
      &lt;/ul&gt;
  &lt;/div&gt;
  </code></pre>
  
  <p>In the database every record has a field called <strong>main_manu</strong> which makes it a main link if the value of this field is <strong>Yes</strong>, and if the value is <strong>No</strong> then it has another field (<strong>sub_menu</strong>) which says the parent menu in which this link should be placed.! See the screenshot.
  <a href="http://i.stack.imgur.com/9l4ii.png" rel="nofollow">DB Fields</a>
  <br><br>
  SO, now I don't know how to do the php piece that will get the records and if the value of the main_menu is yes, it will create a top level menu, and if the value of <strong>main_menu</strong> is no, it will create a sub level menu according to the value of <strong>sub_menu</strong> field.</p>
  
  <p>Thanks a lot </p>
  
  <p><strong>UPDATE</strong></p>
  
  <p>This is the code I have so far and it works. It would be nice if I could use a single query instead of multiple nested queries.</p>
  
  <pre><code>&lt;div id='page-wrap'&gt;
      &lt;ul class='dropdown'&gt;
  &lt;?
  
  $sql_menu = "SELECT * FROM content WHERE visible = '1' and main_menu='yes' ";
  $result_menu = mysql_query($sql_menu); 
  while($row = mysql_fetch_assoc($result_menu))
   {
  $id=$row['id'];
  $menu_top=$row['menu_name'];
  $menu_url=$row['menu_url'];
  
  print "&lt;li&gt;&lt;a href='$menu_url'&gt;$menu_top&lt;/a&gt;";
  
  $sql_sub = "SELECT * FROM content WHERE sub_menu = '$menu_url' ";
  $result_sub = mysql_query($sql_sub);
  $num_rows = mysql_num_rows($result_sub);
  
  while($row = mysql_fetch_assoc($result_sub))
   {
  $id=$row['id'];
  $menu_sub=$row['menu_name'];
  $sub_url=$row['menu_url'];
  If ($num_rows != 0)
  {
  print "&lt;ul class='sub_menu'&gt;
              &lt;li&gt;&lt;a href='$sub_url'&gt;$menu_sub&lt;/a&gt;&lt;/li&gt;
         &lt;/ul&gt;";
  }
  }
  print "&lt;/li&gt;";
  }
  ?&gt;
  &lt;/ul&gt;
  &lt;/div&gt;
  </code></pre>