从多个表中获取信息

时间:2013-05-02 19:02:31

标签: php mysql

目前我可以从配方表中提取配方名称,但我希望能够从配料表中获取所需的配料。我知道这与JOINS有关,但我是JOINS的新手。

这是成分表 This is the ingredients table

这是recipeingredients表,它有两个主键,所以我可以为一个食谱分配多个成分 This is the recipeingredients table, this has two primary keys so I am able to assign multiple ingredients to one recipe

这是食谱表 This is the recipe table

这是搜索脚本

<?php
    $query = $_GET['query'];
    // gets value sent over search form

    $min_length = 3;


    if(strlen($query) >= $min_length){ 

        $query = htmlspecialchars($query);


        $query = mysql_real_escape_string($query);
        // makes sure nobody uses SQL injection

        $raw_results = mysql_query("SELECT * FROM recipes
            WHERE (`recipename` LIKE '%".$query."%') OR (`ingredients` LIKE '%".$query."%')") or die(mysql_error());





        if(mysql_num_rows($raw_results) > 0){ // if one or more rows are returned do following

            while($results = mysql_fetch_array($raw_results)){
            // $results = mysql_fetch_array($raw_results) puts data from database into array, while it's valid it does the loop

                echo "<p>Recipe:".$results['recipename']."</p><p>Ingredients:".$results['ingredients']."<p>Instructions:".$results['instructions']."</p>";
                // posts results gotten from database(title and text) you can also show id ($results['id'])
            }

        }
        else{ // if there is no matching rows do following
            echo "No results";
        }

    }
    else{ // if query length is less than minimum
        echo "Minimum length is ".$min_length;
    }
?>

成分样本数据

enter image description here

配方样本数据

enter image description here

配方表样本数据

enter image description here

1 个答案:

答案 0 :(得分:1)

SELECT
    r.*,
    i.*
FROM recipe AS r
INNER JOIN recipeingredients AS ri
    ON ri.recipeid = r.recipeid
INNER JOIN  ingredients AS i
    ON i.ingredientid = ri.ingredientid
WHERE r.recipename = 'Beans On Toast'

这将为您提供配方及其成分。

EDITS

以下是如何做到这一点。

$query  ="  SELECT
                r.*,
                i.*
            FROM recipe AS r
            INNER JOIN recipeingredients AS ri
                ON ri.recipeid = r.recipeid
            INNER JOIN  ingredients AS i
                ON i.ingredientid = ri.ingredientid
            WHERE r.recipename = 'Beans On Toast'";

$raw_results = mysqli_query($query) or die(mysqli_error());