Display a table in a foreach loop with database values <p>I am trying to display a table in a while loop.. But I have got stuck there for 2 days. anyone can help me to do this? </p> <p>Now I will explain actually what I am trying to do here.. There are several categories and several subjects in my database. each category have its own subjects. Now I need to display category and its subjects as a list. When display subjects under particular category I need to add a HTML table with 2 columns to display subjects..</p> <p>This is the code that I have done so far.. </p> <pre><code> $categoryIds = implode(',', $_SESSION['category']); $q = "SELECT c. category_id AS ci, c.category_name AS cn, s.subject_name AS sn, s.subject_id AS si FROM category AS c INNER JOIN category_subjects AS cs ON cs.category_id = c.category_id INNER JOIN subjects AS s ON s.subject_id = cs.subject_id WHERE c.category_id IN ($categoryIds)"; $r = mysqli_query( $dbc, $q) ; $catID = false; $max_columns = 2; while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) { $categoryId = $row['ci']; $category = $row['cn']; $subjects = $row['sn']; echo '&lt;div&gt;'; //Detect change in category if($catID != $categoryId) { echo "&lt;h3&gt;Category 01: &lt;span&gt;{$category}&lt;/span&gt;&lt;span&gt;&lt;/span&gt;&lt;/h3&gt;\n"; foreach ( $subjects AS $sub ) { echo "&lt;div class='container'&gt;\n"; //echo "&lt;table&gt;&lt;tr&gt;\n"; //echo $sub; echo "&lt;/div&gt; &lt;!-- End .container DIV --&gt;\n"; } echo '&lt;/div&gt;'; } $catID = $categoryId; echo '&lt;/div&gt;'; } </code></pre> <p>Here, Category Name display correctly under tag. But problem is when going to display subjects which are belongs to categories. I am trying to display subjects table in .container Div. </p> <p>please Is anybody there can I get help whit this issue...? </p> <p>Thank you...</p>