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.
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 <code>my_hobbies</code> ( <code>id</code> int(10) NOT NULL AUTO_INCREMENT, <code>hobbies</code> varchar(20) NOT NULL, PRIMARY KEY (<code>id</code>) )
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:
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.