I have a data set which looks similar to:
---------------------------------------------------------------------
id | category | sub_category | category_href | sub_category_href |
01 | cat_1 | sub_cat 1 | cat/cat1.php | cat/cat1/sub_cat1.php|
02 | cat_1 | sub_cat 2 | cat/cat1.php | cat/cat1/sub_cat2.php|
03 | cat_2 | sub_cat 1 | cat/cat2.php | cat/cat2/sub_cat1.php|
04 | cat_2 | sub_cat 2 | cat/cat2.php | cat/cat2/sub_cat2.php|
---------------------------------------------------------------------
What I want to do with the data is have a layout like this:
<div>
<h2 class="title">Cat1</h2>
<p>
<ul class="links">
<li><a href="cat/sub_cat_1.php" target="_top">sub_cat_1</a></li>
<li><a href="cat/sub_cat_2.php" target="_top">sub_cat_2</a></li>
</p>
</div>
<div>
<h2 class="title">Cat2</h2>
<p>
<ul class="links">
<li><a href="cat/sub_cat_1.php" target="_top">sub_cat_1</a></li>
<li><a href="cat/sub_cat_2.php" target="_top">sub_cat_2</a></li>
</p>
</div>
So my question is how would I do this with php so that I can change the categories and sub categories from my db. The following is what I have below but I need a second loop for the sub categories or it will only have one sub category per category. Could someone point me in the right direction for the sub_cat loop. Thank you
EDIT:
So my question is now that I have distinct categories how I can echo the appropriate sub categories?
Thanks
<?php
include('connect.php');
$result = mysql_query("SELECT DISTINCT category FROM categories")
or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
echo "<div>";
echo "<h2 class='title'>" . $row['category'] . "</h2>";
echo "<p>";
echo "<ul class='links'>";
$result1 = mysql_query("SELECT * FROM categories ")
or die (mysql_error());
while ($row = mysql_fetch_array($result1)) {
echo "<li><a href='" . $row['sub_category_href'] . " target='_top'>" . $row['sub_category'] . "</a></li>";
}
echo "</ul>";
echo "</p>";
echo "</div>";
}
?>
mysql_*functions in new code. They were removed from PHP 7.0.0 in 2015. Instead, use prepared statements via PDO or MySQLi. See Why shouldn't I use mysql_* functions in PHP? for more information.