I am attempting to display recipes stored in a mysql database on my site using php. I have 2 tables with the following structure:
recipes:
recipe_id
recipe_name
recipe_instructions
recipe_image
ingredients:
ingredient_id
recipe_id
ingredient_name
What I am attempting to do is to show the recipe name with the ingredients listed underneath.
This code show the recipe_name and the ingredients, but not correctly. For example it will give a list like this:
Basic Salad
2-3 large cucumbers
1/2 c lemon juice
1-2 T tahini
1/3 c chopped onion
2 cloves garlic
1 c mint
1 t sea salt
2 avocados, diced
1 c chopped tomatoes
1/2 c red bell pepper
alfalfa sprouts to top
salad mix
tomatoes
Lemon Flax Dressing
Cool as a Cucumber Soup
when in the database, the ingredients table looks like this:
ingredient_id
recipe_id
ingredient_name
1
1
2-3 large cucumbers
2
1
1/2 c lemon juice
3
1
1-2 T tahini
4
1
1/3 c chopped onion
5
1
2 cloves garlic
6
1
1 c mint
7
1
1 t sea salt
8
1
2 avocados, diced
9
1
1 c chopped tomatoes
10
1
1/2 c red bell pepper
11
1
alfalfa sprouts to top
12
2
salad mix
13
2
tomatoes
14
2
Lemon Flax Dressing
There has to either be an error with how I am querying the data or how I am using the while loops.
Here is the relevant code:
$result = @mysql_query ( 'SELECT * FROM recipes ORDER BY recipe_name' );
$result2 = @mysql_query ( 'SELECT * FROM recipes LEFT JOIN ingredients ON recipes.recipe_id=ingredients.recipe_id' );
if (!$result) {
exit ( '<p>Error performing query: ' . mysql_error() . '</p>' );
}
while ($row = mysql_fetch_array ($result) ) {
echo '<p>' . $row[ 'recipe_name' ] . '</p>' ;
while ($row2 = mysql_fetch_array ($result2) ) {
echo '<p>' . $row2 ['ingredient_name'] . '</p>';
}
}
Why aren't the ingredients showing up under its corresponding recipe_name? Are you not allowed to have nested while loops?
Thanks in advance--