I have a SQL Query:
SELECT mealdesc, group_concat(fooddesc) as fooddesc
FROM plan p
INNER JOIN mealplan mp
ON mp.planid = p.id
INNER JOIN meal m
ON m.id = mp.mealid
INNER JOIN foodmeal fm
ON fm.mealid = m.id
INNER JOIN food f
ON f.id = fm.foodid
where userid = 2
GROUP by mealdesc
order by mealdesc
Results look like this:
mealdesc,fooddesc
Meal 1,"egg,egg whites,oatmeal,wheat toast,fruit,berries"
Meal 2,"Isolyze,raw nuts"
Meal 3,"chicken,turkey,yam,baked potato,veggies,medium salad"
Meal 4,"Isolyze,raw nuts"
Meal 5,"veggies,lean red meat,salmon,Chilean Sea Bass,large salad"
Meal 6,"veggies,large salad,Casein Protein,white fish"
When I remove the group by and group_concat results look like this:
mealdesc,fooddesc
Meal 1,egg
Meal 1,egg whites
Meal 1,oatmeal
Meal 1,wheat toast
Meal 1,fruit
Meal 1,berries
Meal 2,Isolyze
Meal 2,raw nuts
Meal 3,veggies
Meal 3,medium salad
Meal 3,chicken
Meal 3,turkey
...and so on.
Instead of doing a Group by and Group_Concat in the sql statement and having to deal with explode etc. to deal with the delimiters and get it into a php array, is there a way to do this same group by and group_concact logic and organize all this in PHP and push it into an array?
Update:
Thank you for the responses so far. Adding my PHP and HTML sections to this.
I’m basically looking to output each Meal as a Heading and each food in a list. I’ve used explode in the past but I can’t get the array formed right, perhaps thats just my problem.
PHP Code:
$sql = "SELECT mealdesc, group_concat(fooddesc) as fooddesc
FROM plan p
INNER JOIN mealplan mp
ON mp.planid = p.id
INNER JOIN meal m
ON m.id = mp.mealid
INNER JOIN foodmeal fm
ON fm.mealid = m.id
INNER JOIN food f
ON f.id = fm.foodid
where userid = 2
GROUP by mealdesc
order by mealdesc";
$result = mysqli_query($link, $sql);
if (!$result)
{
echo 'Error';
exit();
}
// Fetch food data
while($row = mysqli_fetch_assoc($result)){
$meals[] = array('mealdesc' => $row['mealdesc'], 'fooddesc' => explode(",", $row['fooddesc']));
}
echo '<pre>';
echo print_r($meals, true);
echo '</pre>';
Then in my HTML i loop through like this to output the Meal and food descriptions
<?php foreach ($meals as $meal): ?>
<h4><?php htmlout($meal['mealdesc']); ?></h4>
<ul>
<li><?php htmlout($meal['fooddesc']); ?></li>
</ul>
<?php endforeach; ?>
I’ll assume you used PDO to get your recordset above with a Prepared Statement:
That gives you the following format:
You can then select one in the format you wish by doing:
Output
EDIT
Looking at your code above, you probably want to do the following in your HTML: