I have a form with dynamic inputs, in this case, I take a car owner with multiple cars, so for the same person/client I need to save several cars with the brand name and year model:
<form action="save.php" method="post">
<label for="name">Name of owner</label>
<input type="text" name="name" id="name">
<div class="field_wrapper"> <!--wrapper that help me in the javascript button-->
<label for="car_model">Brand name</label>
<select name="car_model[]" id="car_model">
<option value="ford">Ford</option>
<option value="honda">Honda</option>
<option value="chevrolet">Chevrolet</option>
</select>
<label for="year">Year</label>
<input type="number" name="year[]" id="year">
<input type="button" class= "add_button" value="+" onClick="javascript:void(0);" title="add fields" style="width:25px"></td>
</div>
</form>
I don't know how many cars he/she have, so I used this javascript for add and remove input fields with jQuery:
<script type="text/javascript">
$(document).ready(function(){
var maxField = 5; //Input fields increment limitation
var addButton = $('.add_button'); //Add button selector
var wrapper = $('.field_wrapper'); //Input field wrapper
var fieldHTML = '<div><label for="car_model">Brand name</label><select name="car_model[]" id="car_model"><option value="ford">Ford</option><option value="honda">Honda</option><option value="chevrolet">Chevrolet</option></select><label for="year">Year</label><input type="number" name="year[]" id="year"><input type="button" class= "remove_button" value="-" onClick="javascript:void(0);" title="remove field" style="width:25px"></div>'; //New input field html
var x = 1; //Initial field counter is 1
$(addButton).click(function(){ //Once add button is clicked
if(x < maxField){ //Check maximum number of input fields
x++; //Increment field counter
$(wrapper).append(fieldHTML); // Add field html
} else{
alert('you reach the limit')
}
});
$(wrapper).on('click', '.remove_button', function(e){ //Once remove button is clicked
e.preventDefault();
$(this).parent('div').remove(); //Remove field html
x--; //Decrement field counter
});
});
</script>
What is my goal? in some cases I will have multiple inputs for the same "name" value, So I save the brand name as a array car_model[]
and year[]
.
I understand that I must save in my save.php
something like this:
$name=$_POST['name'];
$array_car=$_REQUEST['car_model'];
$array_year=$_REQUEST['year']
Here comes the problem: how do I save that in my database? I try with a foreach
but looks like is not the rigth way to do it.
Note: I know how to save a "regular" form, I mean, it would be something like:
$query="INSERT INTO cars ('name','car_model','year') VALUES ('$name','$car_model','$year')";
and variables should be:
$name=$_POST['name'];
$car_model=$_POST['car_model'];
$year=$_POST['year'];
but, what about this time? thanks for help, and I hope this time I explain what I need on a better way