I am trying to create a simple css menu that gets the data from a mysql table.
My idea is to have menu like this
Category 1
- link 1
- li
I would use ORDER BY category instead. You can then iterate the result set like
$old = null;
foreach ($st as $s) {
if $old != $s['id']
echo 'Main category';
$old = $s['id'];
echo 'subcategory'
There exist three possible solutions until now in this thread to the problem itself.
SELECT * FROM content group by category
foreach
SELECT * FROM content WHERE category=$cat['category']
If one does only want to get each parent category once, one should use DISTINCT instead. One should not use GROUP BY without using any aggregation function. Combining GROUP BY with SELECT * is limited to (mostly) MySQL. You cannot select arbitrary columns in this case in ASNI SQL.
SELECT DISTINCT category FROM content ORDER BY category
foreach
SELECT * FROM content WHERE category=$cat['category']
This is the corrected version with DISTINCT instead of GROUP BY.
It still lacks of nested query calls. For 5 parent categories, this leads to 5 queries in the loop. For 10 parent categories, there are already 10 queries inside. One should avoid this kind of growing in general.
SELECT * FROM content ORDER BY category, menu_name
usable with the code above.
This is preferable to the other options shown due to different reasons:
There exists an until now unstated further solution. One can use prepared statements, prepare the SQL once and run it with different ids. This would still query all categories inside the loop, but would avoid the necessity to parse SQL code every time.
Actually I do not know if this is better or worse (or sth. in between) than my solution.