I'm using a jQuery plugin to dynamically add input text fields.
The name
of the input elements becomes name="cl[]"
, name="ingredient[]"
.
Now I need to submit these fields to a database somehow...
If there was only one text field that should be added, I guess I could just do a simple foreach
-loop like this:
foreach($ingredient as $val){
// do an ordinary PDO sql insert statement on each of them
}
But I need is to submit two text fields, and the last inserted ID from a previous query, on each of them. If I added two fields, I would have three in total to be submitted; Like this:
<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" />
These fields are ingredients for drinks that is inserted into a sepparate table, and the last id is the relations key.
Any suggestion on how I can accomplish this?
UPDATE:
I just tried to add a hidden textfield with the name raw_materials[]
and do a ẁhile`-loop on that one.
Then do a sql insert statement inside this while loop. Maybe I'm on to something, but this didn't work:
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();
}