Adding Unlimited Form Fields With JQuery and Saving to a Database
In this article I’ll discuss how to add an unlimited number of additional form elements to a form and then save to a database. The latter part is the key here as a variety of tutorials exist on adding form elements, but I have yet to see anywhere that actually explains how to manipulate these added form fields. For example, how to get values to store them in a MySQL datbase. In the example we’ll have a simple user signup form where the user can add multiple fields to describe their favourite websites. The basic Form HTML is as follows (nothing amazing, just a simple html form):
<script src="js/jquery.js" type="text/javascript"></script>
<h1>New User Signup</h1>
<form action="index.php" method="post">
<label for="name">Username:</label>
<input id="name" name="name" type="text" />
<label for="name">Password:</label>
<input id="password" name="password" type="text" />
<div id="container">
<a href="#"><span>» Add your favourite links.....</span></a>
</div>
<input id="go" class="btn" name="btnSubmit" type="submit" value="Signup" />
</form>
The only part that isn’t standard is highlighted above. This is simply the link users click to add additional form fields on the fly. To make that happen we’ll need some JQuery:
var count = 0;
$(function(){
$('p#add_field').click(function(){
count += 1;
$('#container').append('<strong>Link #' + count + '</strong>'+ '<input id="field_' + count + '" name="fields[]' + '" type="text" />' );
});
});
Jquery makes it very easy to add for elements using the append method. As we need to assign a unique name to each additional input (as we are allowing the user to add an indefinite amount of inputs) I’ll use a variable to keep track of the number of inputs added. Whenever an input is added, the counter variable increments by one. Another thing to notice is how the fields are named using ‘txt[]‘. This creates an array of field names. So now when we click the ‘add_field’ link, a new input field is appended to the contianer div – view example.
The only other order of business is to save this information to a database. This would be easy if we had static field names for the whole form, but we don’t. We have the following:
<input id="name" name="name" type="text" /> <input id="password" name="password" type="text" /> <input id="field_1" name="fields[]" type="text" /> <input id="field_2" name="fields[]" type="text" /> <input id="field_3" name="fields[]" type="text" /> . . . etc.
To capture this dynamic fields we’ll need to use a bit of PHP to loop through our posted array and saving the data using a many-many relationships using the following database structure – allowing a user to be associated with an unlimited number of websites:

Many-Many Data Structure For Users And Sites
The following PHP code will grab our static and dynamic form values and insert into the above data structure. We’ll be using a class for the database to minimise the amount of code written. Firstly we’ll check if the forma has actually been submitted, grab the static values (username and password) and insert these into our users table:
//If form was submitted
if (isset($_POST['btnSubmit'])) {
//create instance of database class
$db = new mysqldb();
$db->select_db();
//Insert static values into users table
$sql_user = sprintf("INSERT INTO users (Username, Password) VALUES ('%s','%s')",
mysql_real_escape_string($_POST['name']),
mysql_real_escape_string($_POST['password']) );
$result_user = $db->query($sql_user);
PHP’s sprintf function was used to format the sql query. I also escape input to prevent nasty things from happening. Now we need to check if the user has actually added any favourite websites in order to prevent a php error if we try to find non-existant values, if they have added a field we’ll need the user id number previously inserted into the users table, as we’ll need to insert this elsewhere later on:
//Check if user has actually added additional fields to prevent a php error
if ($_POST['fields']) {
//get last inserted userid
$inserted_user_id = $db->last_insert_id();
Next we loop through the added form field values. This is where naming the field as in our append function as ‘txt[]‘ comes in, as all fields we added are submiited as an array called txt. Using a for each loop we can assign values to all dynamically added fields and save them to database. The $key is simply the fields name (field_1) and the $key is our actual value entered for that field. Now we know this, we can easily generate the sql statements within the loop. Firstly we add the website into the websites table, get the id of the inserted website and insert this into the the link table, using the userid from before. To finish, we display a confirmation message and disconnect from the database:
//Loop through added fields
foreach ( $_POST['fields'] as $key=>$value ) {
//Insert into websites table
$sql_website = sprintf("INSERT INTO websites (Website_URL) VALUES ('%s')",
mysql_real_escape_string($value) );
$result_website = $db->query($sql_website);
$inserted_website_id = $db->last_insert_id();
//Insert into users_websites_link table
$sql_users_website = sprintf("INSERT INTO users_websites_link (UserID, WebsiteID) VALUES ('%s','%s')",
mysql_real_escape_string($inserted_user_id),
mysql_real_escape_string($inserted_website_id) );
$result_users_website = $db->query($sql_users_website);
}
} else {
//No additional fields added by user
}
echo "
<h1>User Added, <strong>" . count($_POST['fields']) . "</strong> website(s) added for this user!</h1>
";
//disconnect mysql connection
$db->kill();
As a result, our database should be populated as follows (these are screenshots from phpmyadmin):

All our data tables are populated and the correct website and user id are inserted into the link table
You can view the source of php file here or download the original source files (you’ll need to open classes/db.class.php and populate the sql variables with your own database details). The MySQL source to create the tables is also included in the source files.
Nice idea, but you should be really using isset when checking if the more fields have been added. For example isset($_POST['fields']).