首页 > 解决方案 > php和mysql从多个表中读取数据

问题描述

这段代码有什么问题。我有 3 个表我试图从中获取数据。一个配方表、一个成分表和一个配方成分表。recipeinredient 保存配方的 ID 和配方的成分。到目前为止,我可以显示来自 recipe 和 recipeingredient 表的数据。现在我正在尝试从成分表中获取数据。

$id = $_GET['id'] ?? ''; //PHP > 7.0
$recipe_id = $id;   
$recipe = find_recipe_by_id($id);
$recipeingredient_set = find_all_recipeingredient_by_recipe_id($recipe_id);

while($recipeingredient = mysqli_fetch_assoc($recipeingredient_set)){
        $ingredient = find_ingredient_by_id($recipeingredient['ingredient_id']);
            echo "<br />    ";
            echo $ingredient['name'];   
            echo "<br />    ";

    } 
    function find_ingredient_by_id($id){
    global $db;

    $sql = "SELECT * FROM Ingredient ";
    $sql .= "WHERE id='" . $id . "'";
    $result = mysqli_query($db, $sql);
    confirm_result_set($result);
    $ingredient = mysqli_fetch_assoc($result);

    return $result; // returns an assoc. array

}
function find_all_recipeingredient_by_recipe_id($recipe_id){
    global $db;

    $sql = "SELECT * FROM RecipeIngredient ";
    $sql .= "WHERE recipe_id='" . $recipe_id . "'";
    $result = mysqli_query($db, $sql);
    confirm_result_set($result);
    return $result;
}   

标签: phpmysqli

解决方案


您正在返回结果而不是数组,只需更新您的返回行

 function find_ingredient_by_id($id){
global $db;

$sql = "SELECT * FROM Ingredient ";
$sql .= "WHERE id='" . $id . "'";
$result = mysqli_query($db, $sql);
confirm_result_set($result);
$ingredient = mysqli_fetch_assoc($result);

return $ingredient; // returns an assoc. array
}

推荐阅读