2013-05-02 93 views
1

目前我能够从食谱表中拉出食谱名称,但我希望能够从配料表中获取所需的配料。我知道这是关于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

recipeingredients样本数据

enter image description here

配方表的样本数据

enter image description here

+0

什么是你想要的输出,并张贴一些示例数据.. – 2013-05-02 19:05:05

+1

如果你是新加入了最明智的做法是了解它,而不是问。 – samayo 2013-05-02 19:05:56

+0

[**请不要在新代码**中使用'mysql_ *'函数](http://bit.ly/phpmsql)。他们不再被维护[并且被正式弃用](http://j.mp/XqV7Lp)。看到[**红框**](http://j.mp/Te9zIL)?学习[*准备的语句*](http://j.mp/T9hLWi),并使用[PDO](http://php.net/pdo)或[MySQLi](http://php.net/ mysqli) - [这篇文章](http://j.mp/QEx8IB)将帮助你决定哪个。 – Kermit 2013-05-02 19:12:58

回答

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()); 
+0

但是,如何将这些内容合并到我的PHP中,以便我可以在表单中输入任何配方,并显示食谱和配料。那是我最初的问题。 我真的很感谢你的帮助。 – 2013-05-02 19:26:00

+0

感谢您的帮助,它不起作用,但这可能是我正在做的一些愚蠢的事情。 – 2013-05-02 19:43:25