<?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; PHP</title>
	<atom:link href="http://www.web-design-talk.co.uk/category/php/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>PHP Paging with Caching</title>
		<link>http://www.web-design-talk.co.uk/210/php-paging-with-caching/</link>
		<comments>http://www.web-design-talk.co.uk/210/php-paging-with-caching/#comments</comments>
		<pubDate>Sat, 03 Jul 2010 11:26:36 +0000</pubDate>
		<dc:creator>Rob</dc:creator>
				<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://www.web-design-talk.co.uk/?p=210</guid>
		<description><![CDATA[The majority of PHP paging script with contain a request to the database for a total row count. This is perfectly acceptable if you script needs an exact and accurate results count. However, most sites don&#8217;t need a dynamic count and the total results count represents an uneeded database request. On busier sites this effect [...]]]></description>
			<content:encoded><![CDATA[<p>The majority of PHP paging script with contain a request to the database for a total row count. This is perfectly acceptable if you script needs an exact and accurate results count. However, most sites don&#8217;t need a dynamic count and the total results count represents an uneeded database request. On busier sites this effect can become quite limiting and will slow down you scripts.</p>
<p>As an example take a website that gets say 10 hit per second, withouit caching this represents 20 (10 hits on your database and 10 hits on your database to fecth the result set) hits per second to your database &#8211; on larger sites and larger result sets  this effect is amplified. However, by simply caching the total number of rows returned you can cut the requests to your database in half. </p>
<p>Google uses a caching system on their results (albeit more more complicated) and they never retuirn the exact amount of results (the perforamnce hit on a site as big and busy as Google would be absolutely huge!). Instead they present results as: &#8220;results 20-40 of about 248,000&#8243; &#8211; with figure of 248,000 coming from an estimated cache value. </p>
<p>To cache the number of results the script would simply store a count of the total number of records in a SESSION variable (assume the cached session value is called &#8220;totalResults&#8221;. You could also store the result as a COOKIE that expires in the future, to force an update the cached number of rows. Using sessions, the code is very simply:</p>
<pre class="brush: php;">
if( !isset($_SESSION['totalResults']) ) {
  //Code to query your database for a row count
} else {
  //use the total record count directly from the session variable
  $myPagerObj-&gt;pageSomeData($_SESSION['total_records'], $perPage, $curPage);
}
</pre>
<p>It would also be wirth doing some validation on the cached page value, for security. However, the latter would usually be done directly in you&#8217;re paging class.  </p>
]]></content:encoded>
			<wfw:commentRss>http://www.web-design-talk.co.uk/210/php-paging-with-caching/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Detect AJAX Requests using the x-requested-with header and xmlhttprequest</title>
		<link>http://www.web-design-talk.co.uk/197/detect-ajax-requests-using-the-x-requested-with-header-and-xmlhttprequest/</link>
		<comments>http://www.web-design-talk.co.uk/197/detect-ajax-requests-using-the-x-requested-with-header-and-xmlhttprequest/#comments</comments>
		<pubDate>Thu, 25 Mar 2010 15:32:47 +0000</pubDate>
		<dc:creator>Rob</dc:creator>
				<category><![CDATA[Ajax]]></category>
		<category><![CDATA[General]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[XAMPP]]></category>

		<guid isPermaLink="false">http://www.web-design-talk.co.uk/?p=197</guid>
		<description><![CDATA[This is a small snippet of code I came across today, it allows a script to display different content based on how it was requested. This method allows your scripts to remain in a single file, handing both AJAX and normal requests &#8211; it avoids ending up with lots of small PHP files in your [...]]]></description>
			<content:encoded><![CDATA[<p>This is a small snippet of code I came across today, it allows a script to display different content based on how it was requested. This method allows your scripts to remain in a single file, handing both AJAX and normal requests &#8211; it avoids ending up with lots of small PHP files in your AJAX folder, that deals with <strong>ajax requests</strong>.Another use would be a page that has 2 web forms, one AJAX and one normal. You could keep the code for this page in a single file. This method is also useful for security purposes, as it would ensure that requests to your AJAX scripts are via AJAX only. It also has uses for writing unobtrusive JavaScript &#8211; maybe ensuring that an AJAX enabled web form would work when javascript is disbaled.</p>
<p>For example, the below code would display different code depending on if the request for the page was made via AJAX or directly via a browser.</p>
<pre class="brush: php;">
if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) &amp;&amp; strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
    //This is an AJAX request, do AJAX specific stuff
}
else {
    //This is not an AJAX request E.g. display normal page content.
}
</pre>
<p>In some code I was working on today, I saw a neater way of achieving the above, this would be included in your common config file:</p>
<pre class="brush: php;">
define('IS_AJAX_REQUEST', isset($_SERVER['HTTP_X_REQUESTED_WITH']) &amp;&amp; strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');

if(IS_AJAX_REQUEST) {
    //This is an AJAX request, do AJAX specific stuff
}
else {
    //This is not an AJAX request E.g. display normal page content.
}
</pre>
<p>There&#8217;s an HTTP variable set called <strong>HTTP_X_REQUESTED_WITH</strong>, which will is set to &#8216;<strong>XMLHttpRequest</strong>&#8216; if the request method is via AJAX. This is method is untested with JavaScript frameworks other than JQuery, so may not work (but I don&#8217;t see any reason at all why it wouldn&#8217;t!).</p>
<p>It&#8217;s also worth noting that not all web servers include this variable and sometimes omit this specific $_SERVER paramter. Use vardump($_SERVER) to check that the <strong>HTTP_X_REQUESTED_WITH</strong> is present.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.web-design-talk.co.uk/197/detect-ajax-requests-using-the-x-requested-with-header-and-xmlhttprequest/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Displaying a Breadcrumb Navigation for Multiple Sub Categories via PHP</title>
		<link>http://www.web-design-talk.co.uk/188/displaying-a-breadcrumb-navigation-for-multiple-sub-categories-via-php-2/</link>
		<comments>http://www.web-design-talk.co.uk/188/displaying-a-breadcrumb-navigation-for-multiple-sub-categories-via-php-2/#comments</comments>
		<pubDate>Mon, 22 Mar 2010 10:57:43 +0000</pubDate>
		<dc:creator>Rob</dc:creator>
				<category><![CDATA[MySQL]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[phpmyadmin]]></category>
		<category><![CDATA[multiple sub categories]]></category>
		<category><![CDATA[php categories]]></category>
		<category><![CDATA[recursive functions]]></category>

		<guid isPermaLink="false">http://www.web-design-talk.co.uk/?p=188</guid>
		<description><![CDATA[While making an ecommerce store I ran into the issue of displaying a category breadcrumb. Usually this is easy as I always recommend keeping the numbers of categories and sub categories to a maximum of 1 level deep. E.g. Tshirts &#62; Red tshirts. For this store, due to the sheer number of products the owner [...]]]></description>
			<content:encoded><![CDATA[<p>While making an ecommerce store I ran into the issue of displaying a category breadcrumb. Usually this is easy as I always recommend keeping the numbers of categories and sub categories to a maximum of 1 level deep. E.g. Tshirts &gt; Red tshirts. For this store, due to the sheer number of products the owner wanted to add up to seven category levels. While there are many tutorials on this floating about, they all seem tocus on displaying the whole tree &#8211; very useful for a sitemap page, but not a breadcrumb navigation. While it would have been possible to hard code several if statements into the category listing page, this seemed a bit messey and would cause problems if an eighth level was added.</p>
<p>For the breadcrumb naviagtion I needed a function to displaying the path to a given category ID, sometimes refered to as a single branch or node. I was using a simple parent child database table structure:</p>
<p><a href="http://www.web-design-talk.co.uk/wp-content/uploads/2010/03/php-multiple-sub-categories.jpg"><img class="size-full wp-image-189 alignnone" style="border: 1px solid #cccccc;" title="php-multiple-sub-categories" src="http://www.web-design-talk.co.uk/wp-content/uploads/2010/03/php-multiple-sub-categories.jpg" alt="php multiple=" /></a></p>
<p>While the latter may seem fairly trival I really couldn&#8217;t get my head around the problem. After a bit of Googling, I found a function that was a good starting point so adapted it to fit my problem (the function is part of a categoru class):</p>
<pre class="brush: php;">
function getCategoryTreeIDs($catID) {
		$row = DB::getInstance()-&gt;query(&quot;SELECT parent FROM categories WHERE ID = '$catID'&quot;)-&gt;fetch();
		$path = array();
		if (!$row['parent'] == '') {
			$path[] = $row['parent'];
			$path = array_merge($this-&gt;getCategoryTreeIDs($row['parent']), $path);
		}
		return $path;
	}
</pre>
<p>The function simply returns an array of category IDs. E.g 20, 28. So from the array I&#8217;d know that the tree would go as Home &gt; Cat ID 20 &gt; Cat ID 28.</p>
<h2 style="font-size:12px;border:0;padding-left:0;">Displaying the Breadcrumb Navigation</h2>
<p>To display the actual breadcrumb I simply added the following method, that loops through the array of ID we just generated. The getNameLink method simply generates an SEO feindly website URL for the category, inside the &lt;a&gt; tag.</p>
<pre class="brush: php;">
function showCatBreadCrumb($catID) {

		$array = $this-&gt;getCategoryTreeIDs($catID);

		$numItems = count($array);
		for ($i = 0; $i&lt;=$numItems-1; $i++) {
			echo $this-&gt;getNameLink($array[$i]) . ' &amp;raquo; ';
		}
	}
</pre>
<p>The result is a nicely formatted breadcrumb (to use our tshiorts example again):</p>
<p>Home &amp;rquao; Clothes &amp;rquao; tshirts &amp;rquao;  Mens &amp;rquao; Red tshirts &amp;rquao; Offensive &amp;rquao;</p>
<h2 style="font-size:12px;border:0;padding-left:0;">A recursive function inside a loop, are you insane?</h2>
<p>Some of you may have noticed that the function used to generate the category IDs is called recursively. This generally considered bad practice, for large data sets due to performance issues. However, for the current use this isn&#8217;t an issue. I know for a fact that client won&#8217;t be adding categories more than several levels deep, so performance really isn&#8217;t an issue in my eyes here. Maybe if we had hundreds of categories, but for several it&#8217;s really a non issue in my opinion.</p>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 185px; width: 1px; height: 1px; overflow: hidden;">
<pre>getCategoryTreeIDs</pre>
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.web-design-talk.co.uk/188/displaying-a-breadcrumb-navigation-for-multiple-sub-categories-via-php-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Process Custom eCommerce data using Paypal IPN</title>
		<link>http://www.web-design-talk.co.uk/141/process-custom-ecommerce-data-using-paypal-ipn/</link>
		<comments>http://www.web-design-talk.co.uk/141/process-custom-ecommerce-data-using-paypal-ipn/#comments</comments>
		<pubDate>Wed, 11 Nov 2009 21:52:08 +0000</pubDate>
		<dc:creator>Rob</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Paypal]]></category>

		<guid isPermaLink="false">http://www.web-design-talk.co.uk/?p=141</guid>
		<description><![CDATA[More often than not it&#8217;s hard to visualise how you can send custom information to Paypal during checkout. The list of available hidden field variables initially seems very specific and restrictive at best. Granted, you can easily send over simple things such as your shipping amountm and tax rate. However, during order processing (done in [...]]]></description>
			<content:encoded><![CDATA[<p>More often than not it&#8217;s hard to visualise how you can send custom information to <a href="http://www.paypal.com/" target="_blank">Paypal</a> during checkout. The list of available <a title="IPN variable list" href="https://cms.paypal.com/us/cgi-bin/?cmd=_render-content&amp;content_ID=developer/e_howto_html_Appx_websitestandard_htmlvariables" target="_blank">hidden field variables</a> initially seems very specific and restrictive at best. Granted, you can easily send over simple things such as your shipping amountm and tax rate. However, during order processing (done in you IPN script that Paypal sends the transaction&#8217;s IPN post data to) you often want to record more information when creating and storingn order information.</p>
<p>For example, let&#8217;s say the user can enter a specific coupon code during checkout. You would want to make sure the Paypal transaction has been successful before making the voucher as used, to do this you would need to know what code was entered during checkout. In the following simple example we&#8217;ll use the &#8216;custom&#8217; field variable  &#8211; this is an optional field, whereby the the data is never presented to the shopper and can be 256 character long. Whatever is placed in this field before clicking your checkout button will be invisibly sent ot Paypal and posted back to your IPN script (assuming you have youre &#8216;rm&#8217; or return method set to 2, or &#8216;POST&#8217;). The HTML for the hidden field is very simple:</p>
<pre class="brush: xml;">
&lt;input type=&quot;hidden&quot; name=&quot;custom&quot; value=&quot;YOUR CUSTOM INFORMATION HERE&quot;&gt;
</pre>
<p>Now, let&#8217;s say when you&#8217;re recording all the order information you weant to record the exact coupon code, delivery method id, the method by which the customer found your site (E.g. another id) and referrer id number. For convenience and for the sake of the example, I&#8217;ll assume you&#8217;ve done all the necessary processing to get your four pieces of information. The code to create our hidden field data is as follows:</p>
<pre class="brush: php;">
/* ...logic to get below variables here! */

$shipping_method_id = '33';
$coupon_code = '45895';
$found_out_method = '9';
$referrer_id = '200';

$custom_info =
                       array(
			'shipping_method_id' =&gt; 33,
			'coupon_code'=&gt; 45895 ,
			'found_out_method' =&gt; 20 ,
			'referrer_id' =&gt; 9
			);

/* Initiase field data and looping variable */
$field_data = NULL;
$i = 0;

/* Loop through info array to build data string */
foreach ($custom_info as $key =&gt; $field) {

	$field_data .= $field;
	$i++;

	if ( $i !== count($custom_info)) {
	      $field_data .= '-';
	}

}

/* create the hidden field
generated HTML is &lt;input type=&quot;hidden&quot; name=&quot;custom&quot; value=&quot;33-45895-20-9&quot;&gt; */
echo '&lt;input type=&quot;hidden&quot; name=&quot;custom&quot; value=&quot;'.$field_data.'&quot;&gt;' . &quot;\n&quot;;
</pre>
<p>Printing the value of $field data will give you the string &#8217;33-45895-20-9&#8242;. This translates to shipping method id 33, coupon code 45895, found out id 20 and referrer id 9. The dash symbol has been used to delimit values for convenience, as we need to split this string up later on.</p>
<p>To process these variables in your IPN script (see the <a href="https://cms.paypal.com/cms_content/US/en_US/files/developer/IPN_PHP_41.txt" target="_blank">Paypal PHP sample script</a>) you simply use PHP&#8217;s explode method to split the data into an array: </p>
<pre class="brush: php;">
/* $_POST['custom'] contains the custom information we initially sent to Paypal */
$data = explode('-',$_POST['custom']);

/* Convert $data array into variables for further processing */
$shipping_method_id = $data[0];
$coupon_code = $data[1];
$found_out_method = $data[2];
$referrer_id = $data[3];
</pre>
<p>So you&#8217;ve now posted a string of custom information to Paypal and got this custom data back via IPN during the transaction processing. Now you have assigned each piece iof the array to a variable, you can easily continue to create your order header and save it to a database. </p>
]]></content:encoded>
			<wfw:commentRss>http://www.web-design-talk.co.uk/141/process-custom-ecommerce-data-using-paypal-ipn/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Getting Multiple Array Form Values With PHP</title>
		<link>http://www.web-design-talk.co.uk/94/getting-multiple-array-form-values-with-php/</link>
		<comments>http://www.web-design-talk.co.uk/94/getting-multiple-array-form-values-with-php/#comments</comments>
		<pubDate>Tue, 18 Aug 2009 21:38:46 +0000</pubDate>
		<dc:creator>Rob</dc:creator>
				<category><![CDATA[JQuery]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[add form inputs]]></category>
		<category><![CDATA[associative array]]></category>
		<category><![CDATA[jquery append]]></category>
		<category><![CDATA[multiple form values]]></category>

		<guid isPermaLink="false">http://www.web-design-talk.co.uk/?p=94</guid>
		<description><![CDATA[Further to my article on using JQuery to dynamically append form elements, I have come across situations where multiple items should be appended to the form each time, as opposed to a single input in my article (I did this simplicity). For example, at work I&#8217;m currently working on an internal system whereby a user [...]]]></description>
			<content:encoded><![CDATA[<div class="wp-caption alignleft" style="width: 130px"><img src="http://www.web-design-talk.co.uk/images/phparray.jpg" alt="php array code" width="120" height="111" /><p class="wp-caption-text">PHP Arrays</p></div>
<p>Further to my <a href="http://www.web-design-talk.co.uk/58/adding-unlimited-form-fields-with-jquery-mysql/">article on using JQuery to dynamically append form elements</a>, I have come across situations where multiple items should be appended to the form each time, as opposed to a single input in my article (I did this simplicity). For example, at work I&#8217;m currently working on an internal system whereby a user needs to add an unlimited amount of client contacts for a client. Pressing the &#8216;add contact&#8217; link will append 3 fields &#8211; one for conatct name, contact telephone and contact email. Each of these fields are named exactly the same way as before (using square brackets at the end of the name E.g. &#8216;name[]&#8216;) and appended the same way using JQuery.</p>
<p>There are lots of articles floating about explaing how to add fields, but I&#8217;ve not yet seen anything explaining how to retreive multiple elements like this.</p>
<p>The only differnce arises when retreiving these multiple values from the PHP&#8217;s POST array. In the example I have appended 3 inputs, named cname[], cemail[] and ctel[]. The values of each can be retreived using a slightly enchanced for loop:</p>
<pre class="brush: php;">
if (isset($_POST['cname'])) {
for ( $i=0;$i&lt;count($_POST['cname']);$i++) {
$contactname = $_POST['cname'][$i];
$conatctemail = $_POST['cemail'][$i];
$contacttel = $_POST['ctel'][$i];
}
}
</pre>
<p>That&#8217;s really all there is to it and I&#8217;m finding that the latter comes in useful quit regularly in every day projects.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.web-design-talk.co.uk/94/getting-multiple-array-form-values-with-php/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<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>29</slash:comments>
		</item>
		<item>
		<title>Simple Ajax Content Loading With JQuery</title>
		<link>http://www.web-design-talk.co.uk/30/simple-ajax-content-loading-with-jquery/</link>
		<comments>http://www.web-design-talk.co.uk/30/simple-ajax-content-loading-with-jquery/#comments</comments>
		<pubDate>Sun, 19 Jul 2009 21:54:33 +0000</pubDate>
		<dc:creator>Rob</dc:creator>
				<category><![CDATA[Ajax]]></category>
		<category><![CDATA[JQuery]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[ajax content loading]]></category>
		<category><![CDATA[ajax load]]></category>
		<category><![CDATA[jquery .load()]]></category>

		<guid isPermaLink="false">http://www.web-design-talk.co.uk/?p=30</guid>
		<description><![CDATA[Occasionally it is useful to silently load content into an area on a webpage. For example, you may have a list of recent comments that you want to refresh every minute. Using a <a href="http://en.wikipedia.org/wiki/Meta_refresh">meta refresh</a> is one option, but this would cause the whole page to refresh, which could annoy the user. The solution is Ajax, where I'll reload the content silently without a single page refresh.]]></description>
			<content:encoded><![CDATA[<div class="wp-caption alignleft" style="width: 239px"><a href="http://www.jquery.com"><img title="JQuery Logo" src="http://www.web-design-talk.co.uk/images/jquery_logo.png" alt="JQuery.com Logo" width="229" height="74" /></a><p class="wp-caption-text">JQuery - JavaScript Framework</p></div>
<p>Occasionally it is useful to silently load content into an area on a webpage. For example, you may have a list of recent comments that you want to refresh every minute. Using a <a href="http://en.wikipedia.org/wiki/Meta_refresh">meta refresh</a> is one option, but this would cause the whole page to refresh, which could annoy the user. The solution is Ajax, where I&#8217;ll reload the content silently without a single page refresh. Even writing the simplist of Ajax functions is quite painful and requires a fair few <a href="http://www.ajaxlines.com/ajax/stuff/article/simple_ajax_javascript_function.php" target="_blank">lines of code</a> to get things done. To make things simpler we&#8217;ll use my favourite JavaScript Framework,  <a href="http://www.jquery.com" target="_blank">JQuery</a>.</p>
<p>The plan is to have dynamic content loaded via Ajax and refresh every x seconds. We&#8217;ll also have a loading image to show the user something is actually happening behind the scenes, as having nothing while the content is loading could make the user leave. The latter is especially important when querying large sets of data, where a delay is possible. You can get your own loading images from the <a href="http://www.ajaxload.info/" target="_blank">ajax loading image site</a>.Now we have a plan, we&#8217;ll get right into it.</p>
<p>First course of action is to setup our basic html page. It&#8217;s nothing amazing, simply a centered divider with a seperate divider for the loading graphic. Here&#8217;s the code we&#8217;ll be using (for simplicity I&#8217;ve used the style tag for the css, as opposed to having a seperate css file:</p>
<p><span id="more-30"></span></p>
<pre class="brush: css; html-script: true;">&lt;!--
	body, h1 {
		font-family: Verdana, Arial, Helvetica, sans-serif;
		font-size: 0.8em;
	}
	a {
		text-decoration: none;
		color: #333;
	}
	a:hover {
		color: #ff0000;
	}

	#ajax-content {
		height: auto;
		width: 400px;
		border: 5px solid #ccc;
		margin: 0 auto;
		padding: 10px;
	}
	#loading {
		width: 66px;
		margin: 0 auto;
	}
--&gt;
&lt;script src=&quot;jquery-1.2.3.min.js&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
&lt;div id=&quot;loading&quot;&gt;
   &lt;img src=&quot;loader.gif&quot; alt=&quot;content is loading&quot; width=&quot;100&quot; height=&quot;100&quot; /&gt;
&lt;/div&gt;
</pre>
<p>The JQuery library has also been included in the header &#8211; you can download JQuery from the <a href="http://jquery.com/">official site</a>. Our actual content will be loaded into the div called &#8216;ajax-content&#8217;. For the content I&#8217;ve simply used an external php file that echos an <a href="http://www.w3schools.com/html/html_lists.asp">un-ordered list</a> and the current server time (you can then see that the content has been refreshed as the time changes). This has been done for simplicity, but you could easily query a database for information. PHP&#8217;s <a href="http://www.php.net/sleep">sleep function</a> was used to create a delay when loading the content, this way you can see something is actually happening. In reality you would never want to use sleep, as it simply delays loading times. The contents of the PHP file are as follows:</p>
<pre class="brush: php;">Last Updated: &quot;.date('h:i:s A').&quot;&quot;;
echo &quot;
&lt;h1&gt;Big List of Software&lt;/h1&gt;
&quot;;
echo &quot;
&lt;ul&gt;
	&lt;li&gt;&lt;a href=&quot;http://link.com&quot;&gt;RmBarCode 1.00a&lt;/a&gt;&lt;/li&gt;
	&lt;li&gt;&lt;a href=&quot;http://link.com&quot;&gt;ServerMask 3.0.4&lt;/a&gt;&lt;/li&gt;
	&lt;li&gt;&lt;a href=&quot;http://link.com&quot;&gt;LinkDeny 1.1.0&lt;/a&gt;&lt;/li&gt;
	&lt;li&gt;&lt;a href=&quot;http://link.com&quot;&gt;Drag Racer 1&lt;/a&gt;&lt;/li&gt;
	&lt;li&gt;&lt;a href=&quot;http://link.com&quot;&gt;Method123 Educational 3.6&lt;/a&gt;&lt;/li&gt;
	&lt;li&gt;&lt;a href=&quot;http://link.com&quot;&gt;Easy St. Tycoon 1.0&lt;/a&gt;&lt;/li&gt;
	&lt;li&gt;&lt;a href=&quot;http://link.com&quot;&gt;iColorPicker 6.18&lt;/a&gt;&lt;/li&gt;
	&lt;li&gt;&lt;a href=&quot;http://link.com&quot;&gt;USB Virus Scan 2.3&lt;/a&gt;&lt;/li&gt;
	&lt;li&gt;&lt;a href=&quot;http://link.com&quot;&gt;AWP Light FREE 2.0&lt;/a&gt;&lt;/li&gt;
	&lt;li&gt;&lt;a href=&quot;http://link.com&quot;&gt;ZipEnable 3.0.2&lt;/a&gt;&lt;/li&gt;
	&lt;li&gt;&lt;a href=&quot;http://link.com&quot;&gt;w3compiler 1.1.2&lt;/a&gt;&lt;/li&gt;
	&lt;li&gt;&lt;a href=&quot;http://link.com&quot;&gt;Remote Reboot 2.0&lt;/a&gt;&lt;/li&gt;
	&lt;li&gt;&lt;a href=&quot;http://link.com&quot;&gt;Pixeur 2.9.0.15&lt;/a&gt;&lt;/li&gt;
	&lt;li&gt;&lt;a href=&quot;http://link.com&quot;&gt;Mailing Master 2.0&lt;/a&gt;&lt;/li&gt;
	&lt;li&gt;&lt;a href=&quot;http://link.com&quot;&gt;Rewards Multiply 2.0&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&quot;;
?&amp;gt;</pre>
<p>Now enters the magic, the JQuery. The following code is placed in script tags in the document head, I&#8217;ll explain line by line how this works.</p>
<pre class="brush: jscript;">function fetchAjaxContent() {
	var numRand = Math.floor(Math.random()*101);
	$('#ajax-content').load('ajax.php?UID=' + numRand);
}</pre>
<p>For simplicity I&#8217;ll add a generic function that load&#8217;s the contents of our PHP file (ajax.php) via Ajax. This simply uses <a href="http://docs.jquery.com/Ajax/load">JQuery&#8217;s load function</a> to load the contents of ajax.php. The random number is placed in the querystring to stop Internet Explorer caching the results. The latter could also be done server side via adding the below to ajax.php:</p>
<pre class="brush:php">header("cache-control: no-cache");</pre>
<p>The following code is placed inside JQuery&#8217;s document ready function. Firstly we hide the divider that will contain the ajax content. using more of JQuery&#8217;s built in ajax function, I use the <a href="http://docs.jquery.com/Ajax/ajaxStart">ajaxStart </a> function (that is executed whenever an AJAX request begins and there is none already active). In this instance the loading image is simply displayed. The opposite function used is <a href="http://docs.jquery.com/Ajax/ajaxStop">ajaxStop </a> (executed whenever all AJAX requests have ended) to hide the loading image and show the loaded content. Finally, we&#8217;ll call our function from previously, &#8216;fetchAjaxContent()&#8217; from within the JavaScript setInterval function (calls a function at specified intervals in milliseconds, every 5 seconds is used in this example). The complete code for the document ready looks like this:</p>
<pre class="brush: jscript;">$(document).ready(function() {

        $('#ajax-content').hide();

	$(&quot;#loading&quot;).ajaxStart(function(){
		$('#ajax-content').slideUp();
                $(this).show();
	});

	$(&quot;#loading&quot;).ajaxStop(function(){
	         $(this).hide();
	         $(&quot;#ajax-content&quot;).slideDown();
	}); 

	setInterval(&quot;fetchAjaxContent()&quot;, 5000);

});</pre>
<p>That&#8217;s it basically. You can now <a href="http://www.web-design-talk.co.uk/examples/1/" target="_self">view a working example</a> or <a href="http://www.web-design-talk.co.uk/examples/1/ajax-content-loading.zip">download the source files</a>. Notice how after each refresh, 5 seconds has elapsed in the printed output.</p>
<p>Thanks for reading!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.web-design-talk.co.uk/30/simple-ajax-content-loading-with-jquery/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
