Dynamically Add Input Fields And Submit To Database With jQuery and PHP

Previously I wrote about adding dynamic input fields in a webpage using jQuery, I got a lot of queries on how to submit it to database. This tutorial is all about generating input fields on the fly in a web page and submitting the entered data into database. For this tutorial let’s assume you have a registration or survey page which asks user to enter his hobbies (hobbies can be multiple). Some have two hobbies and some may have ten, so we will let them enter as many hobbies they want. You can use this tutorial to build more user friendly forms which collect data from users. Let your users create fields on the fly and enter data.

dynamic_input_fields

                Download Code

I have created a sample database “hobbies” having one table “my_hobbies”.  Here is the sql query to generate hobbies table:

SQL query for hobbies table:

</p>
CREATE TABLE IF NOT EXISTS `my_hobbies` (
 `id` int(10) NOT NULL AUTO_INCREMENT,
 `hobbies` varchar(20) NOT NULL,
 PRIMARY KEY (`id`)
)

To connect with database I have created a separate “dbconn.php” file which contains hostname, mysql username and mysql password to connect with database.

Code for dbconn.php:

</p>
<?php
$mysql_db_hostname = "localhost";
$mysql_db_user = "root";
$mysql_db_password = "12345";
$mysql_db_database = "dynamicfield";

$connection = mysql_connect($mysql_db_hostname, $mysql_db_user, $mysql_db_password) or die("Could not connect database");
mysql_select_db($mysql_db_database, $connection) or die("Could not select database");
?>

Our main index.php file contains jQuery and PHP code to submit data into database. To retrieve data entered in newly generated field I have used array “dynfield[]” and then using for each loop pass the retrieved data into sql query.

Code for index.php:

</p>
<?php
require("dbconn.php");
?>

<html>
<head>
<title></title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
var counter = 0;
$(function(){
 $('p#add_field').click(function(){
 counter += 1;
 $('#container').append(
 '<strong>Hobby No. ' + counter + '</strong><br />'
 + '<input id="field_' + counter + '" name="dynfields[]' + '" type="text" /><br />' );

 });
});
</script>

<body>

<?php
if (isset($_POST['submit_val'])) {
if ($_POST['dynfields']) {
foreach ( $_POST['dynfields'] as $key=>$value ) {
$values = mysql_real_escape_string($value);
$query = mysql_query("INSERT INTO my_hobbies (hobbies) VALUES ('$values')", $connection );

}
}

echo "<i><h2><strong>" . count($_POST['dynfields']) . "</strong> Hobbies Added</h2></i>";

 mysql_close();
}
?>
<?php if (!isset($_POST['submit_val'])) { ?>
 <h1>Add your Hobbies</h1>
 <form method="post" action="">

 <div id="container">
 <p id="add_field"><a href="#"><span>Click To Add Hobbies</span></a></p>
 </div>

 <input type="submit" name="submit_val" value="Submit" />
 </form>
<?php } ?>

</body>
</html>

You can use this code in your projects and share this tutorial among your friends. A lot can be done in this code like validation of fields and validation of entered data. Different type of fields like drop down, radio buttons etc can be added in the same way.

61 thoughts on “Dynamically Add Input Fields And Submit To Database With jQuery and PHP”

      1. One thing i want to get clarification on… What if i have season going on my login account i want to submit user_id along with his Hobby prefrence… According to your code im only able to get user hobby and a unique id field for that perticuler hobby… Can you help please

        1. Pratik verma: You can accomplish this by

          First modify the database to include user_id that will be related to the user_id in the user’s table, then

          $userid = $row_loginDetails[‘user_id’];
          if (isset($_POST[‘submit_val’])) {
          if ($_POST[‘dynfields’]) {

          foreach ( $_POST[‘dynfields’] as $key=>$value ) {
          $values = mysql_real_escape_string($value);
          $query = mysql_query(“INSERT INTO my_hobbies (hobbies,user_id) VALUES (‘$values’, ‘$userid’)”, $connection );

          Where $row_loginDetails is a recordset storing user login details

    1. What would the code for the foreach and sql if the form have 2 or more fields to saved to database. I tried foreach with logical AND but it does not work. Please help.

  1. Hii, how to make something like this in php or codeigniter?
    for example i have a combobox containing 1 – 5 (number).
    if i choose 1 in combobox there will be another new combobox containing data from database. if it is chosen 2 there will be 2 other new comboboxes. and so on. later, data in new comboboxes will be saved in database.
    would you like to tell me how to make something like that?
    thank you

    1. Hi wulan, this tutorial is in PHP. I used jquery to generate fields dynamically and then PHP is used to sudmit data into DB. In your case you need to define 5 cases as you have your maximum limit defined ie. 5. So you can have five cases and each case will generate respective number of fields. BTW what do you mean by combobox here?

        1. y i know that your tutorial use php. but, i need php code for such case that i have told you before.

  2. This is really helpful, but how could I extend this to several inputs.

    Plus if I have 100’s of people entering their hobbies how do I know which hobbies applies to which person?

    Thanks.

    1. Hello Steve, I am glad that it helped you. You can have multiple input fields by adding few more lines in the jQuery code and html (It would become lil bit tricky to submit data to database).

      If many peoples are entering their hobbies then you will have to create two tables one will store ‘user name’ and ‘user ID’ and second table will store ‘hobbies’ with respective ‘user ID’. In this way you can fetch all the hobbies for a particular user.

      1. hi sanjeev,
        I hav created the textbox as dynamically bt the problem is after inserted in to the textbox, the value inserted in to the textbox should display it on excel sheet.
        ex:if i enter on my textbox as employee name this employee name should be displayed on the excel sheet.
        plz help me.

        and i m using php and html. ineed to pass a value from php to excel

      1. hi sir i created a new webpage which contains some text boxes such as first_name last_name and etc. so now i want to store that data into database how is it possible… need help sir…??

  3. Hi thanks for the quick reply and the link.

    But perhaps I didn’t explain my needs correctly,

    I have a long form, 5 inputs in this form, may need more than one entry.

    How can I alter your code, to add another input to any or all of these controls.

    ie: inputOne Add
    inputTwo Add
    inputThree Add

    Thanks

    1. Hi Steve, thanks for better explanation of the situation. See here you will have to add five input fields in html form giving them each a unique id and then use javascript/jquery to add new fields(cloned)on user demand. Since each input field has unique id you can easily catch them with your script and if user cliks to add new field you can generate a new field for that particular id only.

  4. Great tutorial sanjeev,

    I am new to PHP and javascript and using this to tweak wordpress. Do I need to mix this tutorial with the related JQuery tutorial or is this stand alone?

    If it is standalone, I don’t see the remove field button in the javascript.

  5. Thank you a lot for this, very helpful!!! Quick question for you… What would it look like if each Hobby line had 3 fields to update 3 separate field in a mysql table? I’m new at this and have been trying to figure it out for a couple days now lol.
    Thanks,

  6. Sanjeev,

    You should make a similar tutorial for wordpress, I believe all you have to do is use:

    update_usermeta( $user_id, ‘name’, $_POST[‘name’] );

    And then if(isset(… { *show hobby* …so they would show up if already set.

    I am new to PHP and trying to accomplish this mixed with francis’ post.

    Looking forward to it.

  7. sir,actually i want to make a form similar to this but there should be two columns unlike one in this
    let me explain to you the format
    item no. product id quantity
    1. delete submit
    2. delete submit
    3. delete submit
    add button(to add more rows)
    the delete and submit buttons delete and submit the data to database respectively,i haven’t used jquery till now but i’m getting your code but not understanding how to make suitable modifications to add column for productid and quantity

    1. actuall the delete and submit buttons should be in the end of the row ,sorry for the above format ,plsss help

  8. Nice Tutorial thanks…

    Can u provide insert update and delete demo of user registration
    with 3 fiels
    user name
    email
    image
    using ajax….
    thanks in advance

  9. I was disable to download above source code, i already subscribe your blog with same email id , please confirm it soon

  10. Hello Sanjeev
    I wish the following:

    1. A data entry form for MySQL
    2. The form field should populate “autosuggest as you type” using
    google like this–> http://googlesuggest-jquery.googlecode.com/svn/trunk/demo.html
    3. Option to add or remove form field like here —> [http://jsfiddle.net/Z4kYf/1/]
    4. When Submit is clicked the form field entries should insert data to MySQL table and newly added field (IF ANY) should add a corresponding field column in MySQL table concerned.

    Question is — can autosuggest result from google be inserted to MySQL using above constraints?
    I am not a coder but I think this can be done. A mashup of the example scripts I have cited should do it perhaps.
    Thanks in advance.

  11. Thank you so much for this wonderful tutorial, its been of great help for me since I am a newbie in jquery and MySQL. Would you please be so kind to provide the jquery code needed in order to show a remove button/link next to each dynamically generated textfield?

  12. milindsuryawanshi001@gmail.com

    hi i want to make vidio gallary means i am storing youtube link in database (mysql) and that link show video on my front page same it is when i am store the link then automatic create video row and display it… r u making this code and send me my email id milindsuryawanshi001@gmail.com ….
    thanx

  13. how about add 2 input at once and insert it, i can add 2 or more input at once but i can’t insert the second or the next with the right value, please help

  14. sanjeev your code is for one filed if we require more fields and delete button when we click on delete button filed which is present in-front of delete should be deleted and store all the details into database
    plz provide solution

  15. can you explain me how to insert values from dynamically generated textboxes in javascript to database in jsp. when we refresh our page then the dynamically generated textboxes disappears.

  16. Hi. You just saved a lot of work for me. I am studying all this but still I need to learn a lot! Would you recommend me any book? How you learn this.
    I just wanted you to know that you are great and you explained everything perfectly! Thanks a lot!
    Congrats for your post!
    Best!

  17. I want Post Multiple post values for foreach function because i have multiple dynamic textbox then how should i send the values??

  18. This is great and I love it. Actually I used this code but do you have an edit option for this? I’m sorry I’m new to PHP. It would be great and much appreciated if you can provide it. Thanks in advance.

  19. THANK YOU, THANK YOU, THANK YOU … you are a Godsend. I’ve been trying to figure this thing out for three days straight. I got the dynamic form fields on my own but how to pass the data into MySQL was the problem and your tutorial was the best amongst all the others I found … *buys Sanjeev a drink*

      1. Sanjeev, I crated the database as per the script, the dbconn.php works, I can echo a response after a connection. I then created a test.php page and pasted your index.php code and saved. However, when I pull the test.php page on my browser, it is blank, nothing happens. any suggestions? I am using an Apache server…

  20. Pingback: Dynamically clone form elements with Cloneya jQuery Plugin - InfoTuts

  21. Hello,

    I am trying to create three text box in a row and insert these text box values in mysql table. but wondering how to do that!!!
    Need your advice to complete this process.

    thanks
    Ripon

  22. Just what i needed! Great article. I’ll use it for a dynamic form in our website. Thanks again.

  23. Nice script, works very perfect! But, what If I my dynamically created table has more than one input, let’s say, Hobbies and Sports and I need to insert both entered results within the database?

    Thank you in advance!

  24. I want to submit data from dynamically added text field in php. but i can handle with one text field with one data base filed but i need to save data from three or five fields to three or five database fields. Help me

    1. use another foreach inside the first foreach,
      e.g foreach ( $_POST[‘XXX’] as $xxxs {
      foreach ( $_POST[‘YYY’] as $yyy

  25. Pingback: Page Not Found - InfoTuts

  26. This has really helped me. However, it would be nice to show how to only insert the data after you have verified that it doesn’t exist in the DB. So something like, loop through all the values and only insert into the db if it doesn’t exist. I would really appreciate it mate, thanks.

  27. Actually i want two text fields like key value pair when i click add button,and want to get those two text field values into a java class or controller.how can i do this.Please help me out regarding this.

  28. how to INSERT multipe field data of clone form in the above example i could insert data but coloumn wise i want to insert in a row

Comments are closed.