我有一个带有动态输入的表格,在这种情况下,我让一位车主拥有多辆汽车,因此对于同一个人/客户,我需要保存几辆带有品牌名称和年份型号的汽车:
<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>
我不知道他/她有多少辆车,所以我用这个 javascript 来添加和删除 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>
我的目标是什么?在某些情况下,我将有多个输入用于相同的“名称”值,因此我将品牌名称保存为数组car_model[]
和year[]
. 我知道我必须保存这样的save.php
东西:
$name=$_POST['name'];
$array_car=$_REQUEST['car_model'];
$array_year=$_REQUEST['year']
问题来了:我如何将它保存在我的数据库中?我尝试使用foreach
但看起来不是正确的方法。注意:我知道如何保存“常规”表单,我的意思是,它类似于:
$query="INSERT INTO cars ('name','car_model','year') VALUES ('$name','$car_model','$year')";
和变量应该是:
$name=$_POST['name'];
$car_model=$_POST['car_model'];
$year=$_POST['year'];
但是,这次呢?感谢您的帮助,我希望这次我能以更好的方式解释我需要什么