I have a database as follows:
---------------------------------------------------------------
| module_name | category | content |
---------------------------------------------------------------
| module1 | category1 | content |
| module2 | category1 | content |
| module3 | category2 | content |
| module4 | category3 | content |
| module5 | category2 | content |
---------------------------------------------------------------
I want to be able to create groups of the results but cannot figure out the quickest and most efficient way to do so without nesting MySQL queries. The result should look like (Styling ignored):
---------------------------------------------------------------
| module1 | category1 | content |
| module2 | category1 | content |
---------------------------------------------------------------
---------------------------------------------------------------
| module3 | category2 | content |
| module5 | category2 | content |
---------------------------------------------------------------
---------------------------------------------------------------
| module4 | category3 | content |
---------------------------------------------------------------
My code looks like:
$query = 'SELECT'
. ' DISTINCT'
. ' category AS name'
. ' FROM #__table'
. ' WHERE enabled = 1';
$db->setQuery($query);
$categories = $db->loadObjectList();
foreach ($categories as $category) {
$query = 'SELECT'
. ' module_name'
. ' FROM #__table'
. ' WHERE enabled = 1 AND category = \'' . $category->name . '\''
. ' ORDER BY id';
$db->setQuery($query);
$results = $db->loadObjectList();
foreach ($results as $result) {
echo $result->module_name;
}
}
This is a nested query that works, but is there a better way to do this?