Dynamic Dropdown menu - PHP <p>First of all, I am new to mysqli and prepare statements so please let me know if you see any error. I have this static drop down menu : <img src="https://i.stack.imgur.com/BJwtZ.png" alt="enter image description here"></p> <p>HTML code:</p> <pre><code>&lt;ul class="menu sgray fade" id="menu"&gt; &lt;li&gt;&lt;a href="#"&gt;Bike&lt;/a&gt; &lt;!-- start mega menu --&gt; &lt;div class="cols3"&gt; &lt;div class="col1"&gt; &lt;ol&gt; &lt;li&gt;&lt;a href="#"&gt;bikes&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;wheels&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;helmets&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;components&lt;/a&gt;&lt;/li&gt; &lt;/ol&gt; &lt;/div&gt; &lt;div class="col1"&gt; &lt;ol&gt; &lt;li&gt;&lt;a href="#"&gt;pedals&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;GPS&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;pumps&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;bike storage&lt;/a&gt;&lt;/li&gt; &lt;/ol&gt; &lt;/div&gt; &lt;div class="col1"&gt; &lt;ol&gt; &lt;li&gt;&lt;a href="#"&gt;power meters&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;hydratation system&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;shoes&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;saddles&lt;/a&gt;&lt;/li&gt; &lt;/ol&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-- end mega menu --&gt; &lt;/li&gt; </code></pre> <p></p> <p>I want to make a dynamic dropdown menu. I managed to show the <code>$categoryName</code> and the <code>$SubCategoryName</code> with this function:</p> <pre><code>function showMenuCategory(){ $db = db_connect(); $query = "SELECT * FROM Category"; $stmt = $db-&gt;prepare($query); $stmt-&gt;execute(); $stmt-&gt;bind_result($id,$categoryName,$description,$pic,$active); while($stmt-&gt;fetch()) { echo'&lt;li&gt;&lt;a href="#"&gt;'.$categoryName.'&lt;/a&gt; &lt;!-- start mega menu --&gt; &lt;div class="cols3"&gt; &lt;div class="col1"&gt; &lt;ol&gt;'; $dba = db_connect(); $Subquery = "SELECT * FROM Subcategory WHERE CategoryId = '".$id."'"; $Substmt = $dba-&gt;prepare($Subquery); $Substmt-&gt;execute(); $Substmt-&gt;bind_result($Subid,$CatId,$SubCategoryName,$SubDescription); while($Substmt-&gt;fetch()) { echo' &lt;li&gt;&lt;a href="#"&gt;'.$SubCategoryName.'&lt;/a&gt;&lt;/li&gt;'; } echo' &lt;/ol&gt; &lt;/div&gt; &lt;!-- end mega menu --&gt; &lt;/li&gt;'; } } </code></pre> <p>The only problem is that it returns all the subcategories on the the same <code>&lt;div class="col1"&gt;</code>:</p> <p><img src="https://i.stack.imgur.com/9ChgN.png" alt="enter image description here"></p> <p>what I would like to obtain is count the subcategories and if the result is more than 4 return the other items in the second and third column. </p> <p>UPDATE***: thanks to the answer below now the menu looks like this:</p> <p><img src="https://i.stack.imgur.com/mqKp4.png" alt="enter image description here"></p> <p>thanks!</p>