I currently have two related tables, one for 'groups' and another for 'items'. Items are stored in groups by an associated group ID. Very basic table relations but unfortunately my SQL is not very good so I'm unsure what is the best way to loop through all groups and, within them, loop through all items to end up with a list of all items categorised by their groups.
Currently I have this code:
$query = "SELECT ID AS GRPID, Description FROM Groups_Inv ORDER BY SortNum ASC";
try {
$result = odbc_exec($connect,$query);
if($result){
while ($groups = odbc_fetch_array($result)) {
echo "<li title='".$groups['DESCRIPTION']."' class='category'>
<h3><span><a class='category'>".
$groups['DESCRIPTION'].
"</a></span></h3><ul class='sub-menu'>\n";
$subquery = "SELECT ID AS ITEM_ID, Description
FROM Items_Inv WHERE grpID = ".$groups['GRPID']."";
$subresult = odbc_exec($connect,$subquery);
while ($items = odbc_fetch_array($subresult)) {
echo "<li class='sub_item' title='".$items['DESCRIPTION']."'>
<input type='radio' class='addRow'>
<label for='".$items['ITEM_ID']."'>".
$items['DESCRIPTION'].
"</label></li>\n";
}
echo "</ul></li>\n";
}
}
else{
throw new RuntimeException("Failed to connect.");
}
}
catch (RuntimeException $e) {
print("Exception caught: $e");
}
I know that having a SQL query within a loop is a very bad idea which is why I would like to optimise this code but my knowledge of SQL is unfortunately pretty limited outside of basic CRUD stuff.
I would also like to be able to not display groups that have no items, but I can't really do that with this code. What would be the best way to be able to get all groups and associated items within one query, as well as being able to specify only selecting groups with associated items?