2010-09-04 35 views
1

打趣我三代表的多個輸入值的查詢: *食譜 - 包含食譜 *成分 - 項目 列表*膳食 - 膳食PHP和MySQL:構建基於從用戶

的名單我有一個表格產生一個選擇,如:

Choose what ingredients you have: 
- apples 
- bananas 
- cherries 

Choose the meal this is for: 
- breakfast 
- lunch 
- dinner 

我希望用戶能夠從任何選擇或沒有以上的,即他們可以選擇蘋果或櫻桃OR(香蕉& &午餐)

當我查詢的MySQL我的查詢是大致

select recipes.* from recipes 

select recipes.* from recipes, ingredients 
where recipes.id= ingredients.id and ingredients.list in ('apple'); 

select recipes.* 
from recipes, ingredients, meal 
where recipes.id= ingredients.id 
     and ingredients.list 
     and ingredients.id = meals.id 
     and ingredients.list ('apple') 
     and meals.list in ('lunch'); 

有沒有說(在PHP)如果此數組存在的一個很好的方式(即is_array(成分)添加到查詢表(成分)和末尾粘性(「('蘋果'中的'.redredients.list))...

而不必編寫所有可能的組合或可能的輸入(即用戶選擇從成分表,或從成分和膳食清單,或者從沒有列出)?

+0

對於一個格式良好的問題+1,特別是對於新用戶!你基本上想要'搜索標準' - 拉「涉及蘋果的所有食譜」和「所有涉及香蕉的午餐食譜」等? – 2010-09-04 10:32:26

+0

你有沒有考慮過使用ORM?它將允許您以很少的努力構建動態查詢。 – DrColossos 2010-09-04 10:34:44

+0

不是很好。實際上它很難讀取很長的一行 – 2010-09-04 10:40:28

回答

0

有解決這一幾種方法。

如果你想知道,如果一個鍵存在你可以使用的數組array_key_exists

+0

我不需要知道一個鍵是否退出,只要該數組存在,並且數組是否在那裏修改查詢字符串。 – Ryank 2010-09-05 16:58:56

0

你可以爲可能的表創建兩個數組,然後在哪裏創建查詢th在收集的一切:

$wheres=array(); 
$tables=array(); 
if(isset($_POST['ingredients'])) { 
    $tables[]='ingredients'; 

    $ingredients=array_map('mysqL_real_escape_string', $_POST['ingredients']); 
    $wheres[]='ingredients.list IN (\''. join(', ', $ingredients). '\')'; 
    //add other wheres if you want 
} 
if(isset($_POST['meals'])) { 
    $tables[]='meal'; 

    $meals=array_map('mysqL_real_escape_string', $_POST['meals']); 
    $wheres[]='meals.list IN (\''. join(', ', $ingredients). '\')'; 
    //add other wheres if you want 
} 

if(!$tables) { 
    echo 'You have not chose anything!'; 
} else { 
    $query = 'SELECT * FROM '. join(',', $tables). ' WHERE '. join(' AND ', $wheres); 
    //do other stuff.. 
} 
+0

這很酷 - 但它不能很好地擴展,假設我可能會返回5個數組,這些數組都可以修改查詢...... – Ryank 2010-09-05 16:59:46

+0

在這種情況下,創建一個數組來鍵入可接受的輸入$ _POST變量,並讓它們各自值:''餐食'=>數組('table'=>'用餐','fieldname'=>'飯食')',例如。並用一個小的簡單循環循環該數組並創建查詢。一旦你想修改你添加一個新的元素到該數組。是不是更酷:) – aularon 2010-09-05 20:46:45

0

我看到沒有「所有可能的組合或可能的投入」在這裏,但只是所有可能的投入。
我會檢查所有可能的輸入並將它們添加到查詢中(如果已填充)。

+0

我想我可以使用sprintf()並修改它,但我希望有一個更具擴展性和優雅的解決方案。 – Ryank 2010-09-05 17:00:50

+0

@賴安嘗試你的「5新陣列」,你會發現它不可能自動完成。每個參數都需要它自己的處理。並不是所有的條件都可以寫成簡單的相等檢查,但其他條件可以使用'between','less','than','like'等。預定義你的所有條件是優雅的。不要根據這樣一個愚蠢的例子來預測未來的使用情況。嘗試首先使用這個更復雜的問題。只有尋找解決方案 – 2010-09-05 17:36:14