I’m really just dipping my toes into the PHP and MySQL waters. I’ve made this work the way I want it to, but I know it’s ugly and I’d like to know how it would be done by someone who actually knows what they’re doing.
function displayCategoryMenu($db){
echo '<ul class="class">';
foreach($db->query('SELECT * FROM categoryDb, thingDb WHERE category = category AND categoryId= "aaa0001" ORDER BY category, thingName') as $row){
if($categoryName!== $row['categoryName']){
$categoryName= $row['CategoryName'];
echo '<li class="category">'.$categoryName.'</li>';
}
echo'<li><a class="fader" href="?&page='.$row['thingId']">'.$row['thingName'].'</a></li>';
}
echo '</ul>';
echo '<ul class="class">';
foreach($db->query('SELECT * FROM categoryDb, thingDb WHERE category = category AND categoryId= "aaa0002" ORDER BY category, thingName') as $row){
if($categoryName!== $row['categoryName']){
$categoryName= $row['CategoryName'];
echo '<li class="category">'.$categoryName.'</li>';
}
echo'<li><a class="fader" href="?&page='.$row['thingId']">'.$row['thingName'].'</a></li>';
}
echo '</ul>';
$db=null;
}
This basically results in an unordered list menu, where the first child acts as a header:
<ul>
<li>category1Name</li>
<li><a>thing</a></li>
<li><a>thing</a></li>
<li><a>thing</a></li>
</ul>
<ul>
<li>category2Name</li>
<li><a>thing</a></li>
<li><a>thing</a></li>
<li><a>thing</a></li>
</ul>
or:
Category1
- Thing
- Thing
- Thing
Category2
- Thing
- Thing
- Thing
and so forth…
The only difference in each ul’s code is the “categoryId” (aaa0001, aaa0002, etc…) I can only imagine that I’m going about this the hard way, with the ugliest code that I can muster. I’d love to see how it should be done.
You should store the list of category ids somewhere in an array, an iterate over that while using a variable in place of the category ID. Something like :
Here the array
$categoryIdscontain the list of IDs you have to display, you can generate it dynamically or pass it as a function parameter as you wish, it’s easily expandable. Theforeachloop iterate over each element of this array and do exactly the same the HTML display and SQL query job for each of the ID denoted by the$categoryIdvariable in the loop.Sidenote about your
$db = null;line : if you don’t pass the$dbfunction parameter as a reference, modifying its value in your function the way yo did it will not have any influence on the original variable, this line is unnecessary here.