I'm trying to build a dynamic PHP / MySQL upload form wherein data fields can be dynamically added or removed, and all of this data can be uploaded to a database from one button.
Here's what this looks like with dynamic <textarea> elements that can be added and removed:
<form method="post" action="dynamicForm.php" enctype="multipart/form-data">
<!--Dynamically Added Paragraphs Go Here-->
<input type="submit" name="upload" value="Upload" id="upload">
</form>
<button onclick="addParagraph()">Add Paragraph</button>
<script>
//add textarea div and associate "Remove" button
function addParagraph(){
$("form").append('<div><textarea name="paragraph"></textarea><button class="remove">Remove</button></div>');
//remove added paragraph
$(document).on('click', ".remove", function(e) {
$(this).parent().remove();
});
</script>
Here's some example PHP that I could use for this:
if (isset($_POST['upload'])) {
$db = mysqli_connect('','','','');
$paragraph = $_POST['paragraph'];
$sql = "INSERT INTO table (paragraph) VALUES ('$paragraph')";
mysqli_query($db, $sql);
}
Each of the added paragraphs have the name paragraph. If there are 5 elements with the name paragraph, and the PHP code is looking for an element with name paragraph, what happens in this situation? Does all the data get uploaded, or just the first element with name paragraph? Will an error be thrown? If this won't upload all the added paragraphs, how can I get the PHP to upload all of them?
EDIT: Possible Solution
<script>
//changed name value to array "paragraph[]"
function addParagraph(){
$("form").append('<div><textarea name="paragraph[]"></textarea><button class="remove">Remove</button></div>');
</script>
if (isset($_POST['upload'])) {
$db = mysqli_connect('','','','');
$sql = "INSERT INTO table (paragraph) VALUES ('$paragraph')";
$paragraph_array = $_POST['paragraph'];
for ($i = 0; $i < count($paragraph_array); $i++){
$paragraph = mysqli_real_escape_string($paragraph_array[$i]);
mysqli_query($db, $sql);
}
}
paragraph[]then iterate over that in the PHP. You also are open to SQL injections, parameterize the query.<form method="post"> action="dynamicForm.php">you need to remove the>after "post".foreachorcountagainst the multi-array. Your edit won't work. The[]belongs in<textarea name="paragraph[]">only. Edit: this comment as per stackoverflow.com/revisions/44752505/2$("form").append('<div><textarea name="paragraph[]"></textarea><button class="remove">Remove</button></div>');. Then iterate over$_POST['paragraph']because it then is an array.