rpivovar
rpivovar

Reputation: 3438

Dynamic PHP / MySQL Upload Form

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);
    }

}

Upvotes: 0

Views: 299

Answers (1)

Once user click upload button, all entered data will be uploaded even though there are multi input elements with the same name.

In the other hand in server side you can only access to the last entered valued in the input element that has the repeated name.

If you want to access to all values you should give input elements different names or just add "[]" at the end of repeated name and in the server side you will get all entered values encapsulated in array.

<?php var_dump($_POST);?>

array(2) { ["paragraph"]=> array(4) { [0]=> string(2) "t1" [1]=> string(2) "t2" [2]=> string(2) "t3" [3]=> string(2) "t4" } ["upload"]=> string(6) "Upload" }

Upvotes: 0

Related Questions