Undefined index PHP/MySQL when trying to query database

This one is not working error problem please help…

Notice:  Undefined index: recipe.id in C:\xampp\htdocs\hyukies\public\samples.php on line 30



Notice:  Undefined index: recipe.ingredientid in C:\xampp\htdocs\hyukies\public\samples.php on line 31

RecipeID: 
IngredientID: 



Notice:  Undefined index: recipe.id in C:\xampp\htdocs\hyukies\public\samples.php on line 30



Notice:  Undefined index: recipe.ingredientid in C:\xampp\htdocs\hyukies\public\samples.php on line 31

RecipeID: 
IngredientID: 



Notice:  Undefined index: recipe.id in C:\xampp\htdocs\hyukies\public\samples.php on line 30



Notice:  Undefined index: recipe.ingredientid in C:\xampp\htdocs\hyukies\public\samples.php on line 31

RecipeID: 
IngredientID: 
<?php 
 $sql_2 = mysqli_query($connection, "SELECT recipe.id, recipe.ingredientid, ingredients.id, ingredients.quantity, ingredients.`name` FROM recipe INNER JOIN ingredients ON ingredients.id = recipe.ingredientid");
 $userinfo_2 = array();
 while ($row_user_2 = mysqli_fetch_assoc($sql_2))
     $userinfo_2[] = $row_user_2;

 foreach ($userinfo_2 as $user_2) {
     echo "RecipeID: {$user_2['recipe.id']}<br />"
     . "IngredientID: {$user_2['recipe.ingredientid']}<br /><br />";
 }

 ?>

var_dump($userinfo_2); should show why you receive those notices.

You shouldn’t add table name in array keys.

For example if you have fields specified with the table name in your query:

SELECT mytable.field1, mytable.field2 FROM mytable

in results array these fields will be available just by name:

$result['field1'];
$result['field2'];

That also means if you want to select two fields with the same name from different tables you should use aliases for them:

SELECT recipe.id as recipe_id, ingredients.id as ing_id ...

result:

$result['recipe_id'];
$result['ing_id'];

Before your foreach, put the following:

var_dump($userinfo_2[0]);

I’m curious what it has for its keys.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.