2012-08-23 44 views
0

我正在使用jQuery插件來動態添加輸入文本字段。 輸入元素的name變爲name="cl[]"name="ingredient[]"如何提交多個輸入文本元素的數組?

現在我需要提交這些字段以某種數據庫...
如果有應添加只有一個文本字段,我想我可以做一個簡單的foreach -loop這樣的:

foreach($ingredient as $val){ 
    // do an ordinary PDO sql insert statement on each of them 
} 

但我需要的是提交兩個文本字段,以及上一個查詢插入的最後一個ID,在他們每個人。 如果我添加了兩個字段,我將總共提交三個字段;像這樣:

<input type="text" name="oz[]" id="cl_1" placeholder="cl" class="cl" > 
<input type="text" name="ingredient[]" id="ingredient_1" placeholder="ingredient name" class="ingredient" /> 

<input type="text" name="oz[]" id="cl_2" placeholder="cl" class="cl" > 
<input type="text" name="ingredient[]" id="ingredient_2" placeholder="ingredient name" class="ingredient" /> 

<input type="text" name="oz[]" id="cl_3" placeholder="cl" class="cl" > 
<input type="text" name="ingredient[]" id="ingredient_3" placeholder="ingredient name" class="ingredient" /> 

這些字段是插入到一個sepparate表中的飲料的成分,最後一個id是關係密鑰。

任何關於如何完成此任務的建議?

更新: 我只是試圖添加一個名爲raw_materials[]的隱藏文本框,並在那個上做了一個「循環」循環。
然後在這個while循環中做一個sql插入語句。也許我是對的,那麼但這並沒有工作:

while($raw_materials){ 
    $ins_ingredients = $con->prepare(
     'INSERT INTO recipes_ingredients (
      recipe_id, raw_material_id, amount 
     ) VALUES (
      :last_id, :material, :amount 
     )' 
    ); 
    $ins_ingredients->bindValues(':last_id',$last_id); 
    $ins_ingredients->bindValues(':material',$ingredient); 
    $ins_ingredients->bindValues(':amount',$oz); 
    $ins_ingredients->execute(); 
} 

回答

2

看看這個:

$values = array_map(null, $_POST['oz'], $_POST['ingredient']); // You can add other arrays after this 
foreach ($values as $value) 
{ 
    list($oz, $ingredient) = $value; 
    // Insert data in DB 
} 
+0

這應該可以做到。我現在無法測試它。但是當我回家時我會測試它... – ThomasK

+0

我有兩張桌子。一個食譜與一些如何的描述。還有另一張桌子,裏面含有該食譜所需的所有原材料。 我在配方表中插入一條記錄,該表中有一個自動增量,我用它來創建另一個原材料的關係... – ThomasK

+0

好吧,一切都很好。 :) – Savageman

1

一組中的CL和配料領域擁有相同的號碼,所以不是foreach循環的,你應該使用一個循環:

for($x=0, $x<count($_POST['cl']); $x++) { 
    // now you can use $_POST['cl'][$x] and $_POST['ingredients'][$x] 
} 
+0

我有種陷在這裏。 我是否首先需要使用'$ last_id'來執行'insert',然後'更新'它以添加cl(oz)和成分? – ThomasK

相關問題