Reputation: 327
Im asking this question and hopefully can simplify it.
I have a custom field generator (using jquery) allowing a price to be set for a particular item. I need to post the values and insert them into a MySQL table row by row with the unique ID (x) as the relationship between drink names and drink prices.
my initial attempt was something on these lines
var max_fields = 50; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var x = 1; //initlal text box count
$(add_button).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++; //text box increment
$(wrapper).append(''
+'<tr class="row_'+x+'">'
+'<td><select style="width:99%;" name="item[product]" ><?php echo $items;?></select></td>'
+'<td><input type="txt" name="item[price]" class="input-small"><input type="hidden" name="item[id]" class="input-small">'
+'<a href="#" class="remove_field pull-right"><span class="icon-cancel"></span></a>'
+'</td>'
+'</tr>');
}
});
when I post this to the server after serializing the inputs this is what is returned
print_r($_POST['item']);
Array
(
[0] => Array
(
[0] => Boags Draught 24 375ml
[1] => Carlton Draught or VB 10/375ml
)
[1] => Array
(
[0] => 12.45
[1] => 45.78
)
[2] => Array
(
[0] => 2
[1] => 3
)
)
How do i insert drinks and unique id into the table?
Upvotes: 2
Views: 267
Reputation: 25862
after our chat we came up with the solution. issue was how the OP was passing data to the server. we had to change the dynamic html input names to be uniform for each product like so
var max_fields = 50; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var x = 1; //initlal text box count
$(add_button).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++; //text box increment
$(wrapper).append(''
+'<tr class="row_'+x+'">'
+'<td><select style="width:99%;" name="item['+x+'][]" ><?php echo $items;?></select> </td>'
+'<td><input type="txt" name="item['+x+'][]" class="input-small"><input type="hidden" name="item['+x+'][]" value="'+x+'" >'
+'<a href="#" class="remove_field pull-right"><span class="icon-cancel"></span></a>'
+'</td>'
+'</tr>');
}
});
then after serializing the form's parameters in the POST $( "#form-package" ).serialize()
the data is sent in this format
Array
(
[2] => Array
(
[0] => Boags Draught 24 375ml
[1] => 12
[2] => 2
)
[3] => Array
(
[0] => Carlton Draught or VB 10/375ml
[1] => 90
[2] => 3
)
)
loop through it like this and you will have the correct solution
foreach($_POST['item'] as $data) {
$insert="INSERT INTO table (meta_id,meta_data) VALUES ('$data[2]','$data[0]')";
$db->setQuery($insert);
$db->query();
}
Upvotes: 1