I'm trying to insert data from dynamically created add remove fields in database using php but unable to do.I'm only able to insert data from original form.
My form lools similar like this.Please help me.
<?php
require_once "conn.php";
$ch_direction= $ch_direction_through==$reg_id="";
if($_SERVER["REQUEST_METHOD"] == "POST"){
for ($i=0; $i < count($_POST['ch_direction']); $i++ )
{
$ch_direction = trim($_POST["ch_direction"][$i]);
$ch_direction_through = trim($_POST["ch_direction_through"][$i]);
$reg_id= $_POST['reg_id'][$i];
$sql = "INSERT INTO bps_registration_charkilla (ch_direction, ch_direction_through,reg_id) VALUES (?, ?, ?)";
if($stmt = mysqli_prepare($conn, $sql)){
mysqli_stmt_bind_param($stmt, "sss",$ch_direction, $ch_direction_through, $reg_id);
$reg_id=$reg_id;
$ch_direction=$ch_direction;
$ch_direction_through=$ch_direction_through;
if(mysqli_stmt_execute($stmt)){
if(!empty($reg_id)){
$success = "Submitted form successfully sent";
header("location: registration_detail.php?success=$success&id=".$reg_id);
exit();
} else {
header("location: registration_detail.php");
exit();
}
} else {
echo "Something went wrong. Please try again later.";
}
}
}
mysqli_close($conn);
}
?>
$(document).ready(function() {
var max_fields = 15; //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 clicf k
e.preventDefault();
if(x < max_fields) { //max input box allowed
x++; //text box increment
$('.input_fields_wrap').append('<div class="row"><div class="col-md-6"><div class="form-group"><label for="">City</label><input type="hidden" value="<?php echo $_GET['id'];?>" name="reg_id[]"><select name="ch_direction[]" class="form-control" ng-model="ch.ch_direction" required><option value="n">उत्तर</option> <option value="e">पुर्व</option> <option value="s">दक्षिण</option><option selected="selected" value="w">पश्चिम</option> </select></div><div class="form-group"><label for="">Email</label><select name="ch_direction_through[]" class="form-control" ng-model="ch.ch_direction_through"><option value="front">Front</option><option value="back">Back</option><option value="left">Left</option><option selected="selected" value="right">Right</option></select></div></div><div style="cursor:pointer;background-color:red;" class="remove_field btn btn-info">Remove</div></div>'); //add input box
}
});
$(wrapper).on("click",".remove_field", function(e) { //user click on remove text
e.preventDefault();
$(this).parent('div').remove(); x--;
});
});
Because you have a header the code will insert single row and do the header to the requested file. So, remove both the header.
You assign variables within a loop, but insert into database only once after the loop. Put your database insertion into the loop, as follows (I keep it short for better understanding of the idea):