You have a PHP form with multiple input fields whose quantity is user-defined. To effectively enter this data into a database, Ajax is a viable solution. Here's a solution tailored to your specific scenario.
Implement the following Ajax function to fulfill your requirement:
function MyFunction(){ var i = 1; var x = $('#num_to_enter').val(); var formData = new FormData; while (i <= x){ var name = $('#fname[i]').val(); var lname = $('#lname[i]').val(); var email = $('#Email[i]').val(); formData.append("fname[" + i + "]", name); formData.append("lname[" + i + "]", lname); formData.append("email[" + i + "]", email); i++; } $.ajax({ url: 'process.php', type: "POST", data: formData, processData: false, contentType: false, success : function(data){ window.setTimeout(function() { $('#SuccessDiv').html('Info Added!'); $('#data').css("display","block"); $('#data').html(data); }, 2000); } }); return false; }
Your provided form structure remains valid:
echo "<form method='post'>"; $i=1; while($i <= $num_to_enter){ $form_output .= "First Name: <input>
Within your database insertion script, ensure to include the Ajax data accordingly:
while ($i <= $x){ $x = $_POST['num_to_enter']; $fname = $_POST['fname[$i]']; $lname = $_POST['lname[$i]']; $email = $_POST['email[$i]']; $sql = "INSERT INTO `mytable` (`firstname`, `lastname`, `email`) VALUES ('$fname[$i]', '$lname[$i]', '$email[$i]');"; $i++; }
This Ajax-enabled solution efficiently captures user input from the dynamically generated form and forwards it to your PHP script for database insertion.
The above is the detailed content of How to Use Ajax and PHP to Populate a Database from a Dynamic Form with Multiple Inputs?. For more information, please follow other related articles on the PHP Chinese website!