<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Web Design Talk &#187; pgp</title>
	<atom:link href="http://www.web-design-talk.co.uk/tag/pgp/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.web-design-talk.co.uk</link>
	<description>Web Design &#38; Development Blog</description>
	<lastBuildDate>Wed, 28 Jul 2010 21:50:39 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>Adding Unlimited Form Fields With JQuery and Saving to a Database</title>
		<link>http://www.web-design-talk.co.uk/58/adding-unlimited-form-fields-with-jquery-mysql/</link>
		<comments>http://www.web-design-talk.co.uk/58/adding-unlimited-form-fields-with-jquery-mysql/#comments</comments>
		<pubDate>Sat, 25 Jul 2009 20:36:49 +0000</pubDate>
		<dc:creator>Rob</dc:creator>
				<category><![CDATA[JQuery]]></category>
		<category><![CDATA[MySQL]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[associative array]]></category>
		<category><![CDATA[dynamic form fields]]></category>
		<category><![CDATA[pgp]]></category>
		<category><![CDATA[sprintf]]></category>

		<guid isPermaLink="false">http://www.web-design-talk.co.uk/?p=58</guid>
		<description><![CDATA[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):]]></description>
			<content:encoded><![CDATA[<p>In this article I&#8217;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&#8217;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):</p>
<pre class="brush: xml; highlight: [10,11,12];">
&lt;script src=&quot;js/jquery.js&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
&lt;h1&gt;New User Signup&lt;/h1&gt;
&lt;form action=&quot;index.php&quot; method=&quot;post&quot;&gt;

  &lt;label for=&quot;name&quot;&gt;Username:&lt;/label&gt;
  &lt;input id=&quot;name&quot; name=&quot;name&quot; type=&quot;text&quot; /&gt;
  &lt;label for=&quot;name&quot;&gt;Password:&lt;/label&gt;
  &lt;input id=&quot;password&quot; name=&quot;password&quot; type=&quot;text&quot; /&gt;

   &lt;div id=&quot;container&quot;&gt;
      &lt;a href=&quot;#&quot;&gt;&lt;span&gt;» Add your favourite links.....&lt;/span&gt;&lt;/a&gt;
   &lt;/div&gt;

   &lt;input id=&quot;go&quot; class=&quot;btn&quot; name=&quot;btnSubmit&quot; type=&quot;submit&quot; value=&quot;Signup&quot; /&gt;
&lt;/form&gt;
</pre>
<p>The only part that isn&#8217;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&#8217;ll need some <a href="http://www.JQuery" target="_blank">JQuery</a>:</p>
<pre class="brush: jscript;">
var count = 0;
$(function(){
	$('p#add_field').click(function(){
		count += 1;
		$('#container').append('&lt;strong&gt;Link #' + count + '&lt;/strong&gt;'+ '&lt;input id=&quot;field_' + count + '&quot; name=&quot;fields[]' + '&quot; type=&quot;text&quot; /&gt;' );
	});
});</pre>
<p><span id="more-58"></span></p>
<p>Jquery makes it very easy to add for elements using the <a href="http://docs.jquery.com/Manipulation/append" target="_blank">append </a>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&#8217;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 &#8216;txt[]&#8216;. This creates an array of field names. So now when we click the &#8216;add_field&#8217; link, a new input field is appended to the contianer div &#8211; <a href="http://www.web-design-talk.co.uk/examples/2/1/" target="_self">view example</a>.</p>
<p>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&#8217;t. We have the following:</p>
<pre class="brush: xml;">&lt;input id=&quot;name&quot; name=&quot;name&quot; type=&quot;text&quot; /&gt;
&lt;input id=&quot;password&quot; name=&quot;password&quot; type=&quot;text&quot; /&gt;
&lt;input id=&quot;field_1&quot; name=&quot;fields[]&quot; type=&quot;text&quot; /&gt;
&lt;input id=&quot;field_2&quot; name=&quot;fields[]&quot; type=&quot;text&quot; /&gt;
&lt;input id=&quot;field_3&quot; name=&quot;fields[]&quot; type=&quot;text&quot; /&gt;
.
.
.
etc.</pre>
<p>To capture this dynamic fields we&#8217;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 &#8211; allowing a user to be associated with an unlimited number of websites:</p>
<div class="wp-caption alignnone" style="width: 510px"><img title="Data Structure For Users And Sites" src="http://www.web-design-talk.co.uk/images/users_sites.jpg" alt="Many-Many Data Structure For Users And Sites" width="500" height="125" /><p class="wp-caption-text">Many-Many Data Structure For Users And Sites</p></div>
<p>The following PHP code will grab our static and dynamic form values and insert into the above data structure. We&#8217;ll be using a class for the database to minimise the amount of code written. Firstly we&#8217;ll check if the forma has actually been submitted, grab the static values (username and password) and insert these into our users table:</p>
<pre class="brush: php;">//If form was submitted
if (isset($_POST['btnSubmit'])) {

	//create instance of database class
	$db = new mysqldb();
	$db-&amp;gt;select_db();

	//Insert static values into users table
	$sql_user = sprintf(&quot;INSERT INTO users (Username, Password) VALUES ('%s','%s')&quot;,
						mysql_real_escape_string($_POST['name']),
						mysql_real_escape_string($_POST['password']) );
	$result_user = $db-&amp;gt;query($sql_user);</pre>
<p>PHP&#8217;s <a href="http://www.php.net/sprintf">sprintf</a> function was used to format the sql query. I also escape input to prevent <a href="http://en.wikipedia.org/wiki/SQL_injection">nasty things from happening</a>. 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&#8217;ll need the user id number previously inserted into the users table, as we&#8217;ll need to insert this elsewhere later on:</p>
<pre class="brush: php;">//Check if user has actually added additional fields to prevent a php error
	if ($_POST['fields']) {

		//get last inserted userid
		$inserted_user_id = $db-&amp;gt;last_insert_id();</pre>
<p>Next we loop through the added form field values. This is where naming the field as in our append function as &#8216;txt[]&#8216; 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:</p>
<pre class="brush: php;">//Loop through added fields
		foreach ( $_POST['fields'] as $key=&amp;gt;$value ) {

			//Insert into websites table
			$sql_website = sprintf(&quot;INSERT INTO websites (Website_URL) VALUES ('%s')&quot;,
						    	   mysql_real_escape_string($value) );
			$result_website = $db-&amp;gt;query($sql_website);
			$inserted_website_id = $db-&amp;gt;last_insert_id();

			//Insert into users_websites_link table
			$sql_users_website = sprintf(&quot;INSERT INTO users_websites_link (UserID, WebsiteID) VALUES ('%s','%s')&quot;,
						    	   mysql_real_escape_string($inserted_user_id),
								   mysql_real_escape_string($inserted_website_id) );
			$result_users_website = $db-&amp;gt;query($sql_users_website);

		}

	} else {

		//No additional fields added by user

	}
	echo &quot;
&lt;h1&gt;User Added, &lt;strong&gt;&quot; . count($_POST['fields']) . &quot;&lt;/strong&gt; website(s) added for this user!&lt;/h1&gt;
&quot;;

	//disconnect mysql connection
	$db-&amp;gt;kill();</pre>
<p>As a result, our database should be populated as follows (these are screenshots from phpmyadmin):</p>
<div class="wp-caption alignnone" style="width: 510px"><img class=" " title="Many to many relationship" src="http://www.web-design-talk.co.uk/images/users_websites_data.jpg" alt="All our data tables are populated and the correct website and user id are inserted into the link table" width="500" height="278" /><p class="wp-caption-text">All our data tables are populated and the correct website and user id are inserted into the link table</p></div>
<p>You can view the <a href="http://www.web-design-talk.co.uk/examples/2/index-source.php">source of php file here</a> or <a href="http://www.web-design-talk.co.uk/examples/2/adding-form-elements-with-jquery.zip">download the original source files</a> (you&#8217;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.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.web-design-talk.co.uk/58/adding-unlimited-form-fields-with-jquery-mysql/feed/</wfw:commentRss>
		<slash:comments>34</slash:comments>
		</item>
	</channel>
</rss>
