2013-05-02 109 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