DEV Community

Nachiket Panchal
Nachiket Panchal

Posted on • Originally published at errorsea.com on

How to Add Unlimited Fields in Form Using JavaScript and Store Into Database With PHP

Sometimes we need to add unlimited fields into our form for better user experience. At that time, we can put an ADD FIELD button into the page for dynamic field generation on a webpage.

Creating unlimited fields in the form is effortless using JavaScript and jQuery. In addition, saving the data into a database is also easy to handle with PHP.

Adding Unlimited Fields Using JS and Saving Using PHP

Here we are going to use JavaScript to add new fields and PHP to save data into the database.

Step: Create a form and add a function to add new dynamic fields

<!DOCTYPE html>
<html>
    <body>
        <form id="form" method="POST" action="save_data.php">
            <input type="text" name="text_field[]">
            <button type="submit">SUBMIT</button>
        </form>
        <button onclick="add_field()">ADD FIELD</button>
        <script>
            function add_field(){

                var x = document.getElementById("form");
                // create an input field to insert
                var new_field = document.createElement("input");
                // set input field data type to text
                new_field.setAttribute("type", "text");
                // set input field name 
                new_field.setAttribute("name", "text_field[]");
                // select last position to insert element before it
                var pos = x.childElementCount;

                // insert element
                x.insertBefore(new_field, x.childNodes[pos]);
            }
        </script>
    </body>
</html>
Enter fullscreen mode Exit fullscreen mode

Explanation

Here we created a function named add_field to append a text field at the second last position in the form.

Note: Here, we set every field name as text_field[], which submits all text field data as an array.

Step 2: Create a save_data.php file to store the data to the database

<?php
    $conn = mysqli_connect("localhost","USER_NAME","PASSWORD","DATABASE_NAME");

    $data = $_POST['text_field'];
    $data = implode(",",$data);

    $query = "INSERT INTO `test`(`data`) VALUES ('$data')";
    if(mysqli_query($conn,$query)){
        echo "Success: Data successfully inserted";
    }else{
        echo "Error: Could not insert data into table";
    }
?>
Enter fullscreen mode Exit fullscreen mode

Explanation

  • Here we first stored the submitted array data in a PHP array variable named $data.
  • After that, we used an inbuilt PHP function implode(), which converts an array into a PHP string.
  • Finally, we saved our string data to our data table.

DOWNLOAD CODE

Conclusion

Creating unlimited dynamic fields is very easy using JavaScript. Even more, we learned a way to store that dynamic data into a database using some simple functions of PHP.

I hope now you have a complete understanding of dynamic field insertion and data storing techniques.

Enjoy Coding 🙂

The post Add Unlimited Fields in Form Using JavaScript and PHP appeared first on errorsea.

Top comments (6)

Collapse
 
smokeysbar profile image
Smokey´s Bar Fuengirola

Great post, works like a charm and (almost) exactly what I need

I got it to work to add 2 select fields, here's the thing, building an ordering system for my bar so I can order easy from my providers.

So I have 2 select boxes, 1 is for the amount and 2 is for the product.

That way I can select for example 5 boxes of beer, add a new row of select boxes and order more stuff, and then submit so it saves in DB and sends a mail to my provider so I get the order delivered.

So I have 2 arrays, 1 for amounts and 1 for products.

How do I enter 2 arrays in the DB?

Thanks in advance for any help, Greetings from Spain

Collapse
 
adnanbabakan profile image
Adnan Babakan (he/him)

Thanks for sharing this!
But I think your code is subject to some good SQL Injection and XSS attacks! xD

Collapse
 
nachiket profile image
Nachiket Panchal

Of course, I've posted it for novice programmers who are looking for a straight forward logic. After understanding the logic, they can implement some advance scripting :)

Collapse
 
adnanbabakan profile image
Adnan Babakan (he/him)

Uh nice! Excuse my saying but I suggest you add a line that warns them somehow.
Love your posts.

Thread Thread
 
nachiket profile image
Nachiket Panchal

Ya sure, thanks for your suggestion.
Now I am planning to write a separate post on security.

Collapse
 
pankajhue profile image
Pankaj Kumar

Hi, Can You please help me to create a db class to submit data in database using __construct and insert, select, delete and update function.