<?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>Bagesh Singh&#039;s Blog &#187; tutorial</title>
	<atom:link href="http://www.bageshsingh.com/bagesh-blog/category/tutorial/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.bageshsingh.com/bagesh-blog</link>
	<description>Shortest Distance to  Web Solutions &#38; Software Solutions</description>
	<lastBuildDate>Wed, 22 Feb 2012 18:42:12 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>Canada’s postal code validation in PHP</title>
		<link>http://www.bageshsingh.com/bagesh-blog/2011/08/canada%e2%80%99s-postal-code-validation-in-php/</link>
		<comments>http://www.bageshsingh.com/bagesh-blog/2011/08/canada%e2%80%99s-postal-code-validation-in-php/#comments</comments>
		<pubDate>Mon, 29 Aug 2011 17:47:45 +0000</pubDate>
		<dc:creator>Bagesh Singh</dc:creator>
				<category><![CDATA[Home]]></category>
		<category><![CDATA[how-to]]></category>
		<category><![CDATA[Interview Question]]></category>
		<category><![CDATA[Others]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[Php interview question]]></category>
		<category><![CDATA[tips and technique]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[canada postal code]]></category>
		<category><![CDATA[validation]]></category>

		<guid isPermaLink="false">http://www.bageshsingh.com/bagesh-blog/?p=1468</guid>
		<description><![CDATA[Few days back, My friend Narendra asked me how to validate the postal code of Canada which is entered through the text box.And, I came up with this Php function as solution for him. &#160; These are the conditions for validation of the postal code of Canada. There are six alphanumeric letters. Alphabate and digits [...]]]></description>
			<content:encoded><![CDATA[<p align="justify">Few days back, My friend Narendra asked me how to validate the postal code of Canada which is entered through the text box.And, I came up with this Php function as solution for him.</p>
<p>&nbsp;</p>
<p align="justify">
<p align="justify">These are the conditions for validation of the postal code of Canada.</p>
<ol>
<li>There are six alphanumeric letters.</li>
<li>Alphabate and digits are alternate and first letter must be alphabate.</li>
<li>The alphabate shouldn’t contain letters “d”,”f”,”i”,”o”,”q” and “u”.</li>
</ol>
<p align="justify">Postal code “<strong>A1B2c5</strong>” is a valid postal code whereas “<strong>A1f2cZ</strong>” or “<strong>1AC2E5</strong>” are invalid postal code of Canada.</p>
<pre>//function to validate postal code of canada
function validateCanadaZip($zip_code)
{
 //function by Roshan Bhattara(http://roshanbh.com.np)
 if(preg_match("/^([a-ceghj-npr-tv-z]){1}[0-9]{1}[a-ceghj-npr-tv-z]{1}[0-9]{1}[a-ceghj-npr-tv-z]{1}[0-9]{1}$/i",$zip_code))
    return true;
 else
    return false;
}</pre>
<p align="justify">Now, let’s look at the explanation of the regular expression inside the preg_match() to validate the postal code of Canada as specified by the above condition. As you might know that a Perl compatible regular expression enclosed within “/” sign. The “i” at the end of the expression refers that this comparison is case insensitive.As most of you know, “^”sign is the start of the regular expression and “$” represent the end of the regular expression. And there are three repeated expressions like “([a-ceghj-npr-tv-z]){1}[0-9]{1}”. Let me explain it, the expression “([a-ceghj-npr-tv-z]){1}” represents that there should be one alphabate which doesn’t contain “d”,”f”,”i”,”o”,”q” and “i”. Furthermore, the expression “[0-9]{1}” represents that there should be one digit.</p>
<div id="seo_alrp_related"><h2>Posts Related to Canada’s postal code validation in PHP</h2><ul><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/08/usa%e2%80%99s-zip-code-validation-in-php/" rel="bookmark">USA’s Zip Code Validation in PHP</a></h3><p>My friend Sushil was trying to write the regular expression for validating the format of the zip code of USA. After spending few minutes, I ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/08/ip-address-validation-in-php-using-regular-expression/" rel="bookmark">Ip address validation in PHP using regular expression</a></h3><p>If you don’t know how to validate the IP address format in PHP, then you are in the right place.I’ll show you here how to ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/08/how-to-do-date-format-validation-in-php/" rel="bookmark">How to do Date format validation in PHP</a></h3><p>Today Sushil asked me how can we validate the date which is entered from textbox in “YYYY-MM-DD” format. Well, we can validate the format of ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/05/php-regular-expression-regex-functions-list/" rel="bookmark">PHP Regular Expression (Regex) Functions List</a></h3><p>Perl-Compatible Functions List preg_grep — Return array entries that match the pattern preg_match_all — Perform a global regular expression match preg_match — Perform a regular ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/08/understanding-and-validating-integers-in-php/" rel="bookmark">Understanding and Validating Integers in PHP</a></h3><p>I’ve found many of my friends struggling with the validation of integers i.e. the numbers with only digits in PHP. Some of them were wondering ...</p></div></li></ul></div>]]></content:encoded>
			<wfw:commentRss>http://www.bageshsingh.com/bagesh-blog/2011/08/canada%e2%80%99s-postal-code-validation-in-php/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Textbox to accept only numbers (digits) using jquery</title>
		<link>http://www.bageshsingh.com/bagesh-blog/2011/08/textbox-to-accept-only-numbers-digits-using-jquery-2/</link>
		<comments>http://www.bageshsingh.com/bagesh-blog/2011/08/textbox-to-accept-only-numbers-digits-using-jquery-2/#comments</comments>
		<pubDate>Mon, 29 Aug 2011 17:45:47 +0000</pubDate>
		<dc:creator>Bagesh Singh</dc:creator>
				<category><![CDATA[Home]]></category>
		<category><![CDATA[how-to]]></category>
		<category><![CDATA[Interview Question]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[JQuery Interview Questions]]></category>
		<category><![CDATA[Others]]></category>
		<category><![CDATA[tips and technique]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://www.bageshsingh.com/bagesh-blog/?p=1464</guid>
		<description><![CDATA[Few days back, my friend Parleen asked me how can we make a textbox which just accepts only numbers specially digits only. And, for his I come up with this solution of textbox which only accepts digits, and if you try to enter any alpha bates in it then it displays the error message with [...]]]></description>
			<content:encoded><![CDATA[<p align="justify">Few days back, my friend Parleen asked me how can we make a textbox which just accepts only numbers specially digits only. And, for his I come up with this solution of textbox which only accepts digits, and if you try to enter any alpha bates in it then it displays the error message with animation.</p>
<p>&nbsp;</p>
<p align="justify"><strong>View Demo </strong></p>
<p align="justify"><strong>HTML Code </strong></p>
<pre>&lt;input type="text" name="quantity" id="quantity" /&gt; &lt;span id="errmsg"&gt;&lt;/span&gt;</pre>
<p align="justify">As you can see above, I’ve given the name and id of textbox to “quantity” in this example.This is the textbox which only accepts numbers (digits only). You can see “span” after textbox which is used to display the error message with fading effect using jQuery.</p>
<p align="justify"><strong>Javascript Code </strong></p>
<p align="justify">First of all, we need to use jQuery library as we’re using the jquery’s function to accept only digits.</p>
<pre>&lt;script type="text/javascript" src="jquery.js"&gt;&lt;/script&gt;</pre>
<p align="justify">Now le’ts write the code in JavaScript using jQuery to accept only digits in textbox and displaying error with animation.</p>
<pre>//when key is pressed in the textbox$("#quantity").keypress(function (e)
{
  //if the letter is not digit then display error and don't type anything
  if( e.which!=8 &amp;&amp; e.which!=0 &amp;&amp; (e.which&lt;48 || e.which&gt;57))
  {
    //display error message
    $("#errmsg").html("Digits Only").show().fadeOut("slow");
    return false;
  }
});</pre>
<p align="justify">When the key is pressed, we’re using the key’s ASCII value to check which button is pressed. In first expression, delete, tab or backspace button is is checked and “8″ is the ASCII values of the Back-space. Digits are checked in the second expression. “48″ is the ASCII values of “0″ and “57″ is the ASCII values of “9″. The the ASCII values of the other digits lies between “48″ to “57″. And, if the key pressed values doesn’t lies withing these range, then we are displaying the error message with jQuery’s fading effect.</p>
<p align="justify">And, the “return false” statement means that this functions returns false values which means not to type anything on the text box.</p>
<p align="justify"><strong><a href="http://roshanbh.com.np/codes/accept-only-digit.zip" target="_blank">Download Full Source Code</a> </strong></p>
<div id="seo_alrp_related"><h2>Posts Related to Textbox to accept only numbers (digits) using jquery</h2><ul><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2010/03/textbox-to-accept-only-numbers-digits-using-jquery/" rel="bookmark">Textbox to accept only numbers (digits) using jquery</a></h3><p>Few days back, my friend Parleen asked me how can we make a textbox which just accepts only numbers specially digits only. And, for his ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/08/understanding-and-validating-integers-in-php/" rel="bookmark">Understanding and Validating Integers in PHP</a></h3><p>I’ve found many of my friends struggling with the validation of integers i.e. the numbers with only digits in PHP. Some of them were wondering ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/08/ip-address-validation-in-php-using-regular-expression/" rel="bookmark">Ip address validation in PHP using regular expression</a></h3><p>If you don’t know how to validate the IP address format in PHP, then you are in the right place.I’ll show you here how to ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/02/get-and-set-form-element-values-using-jquery/" rel="bookmark">Get and Set Form Element Values using jQuery</a></h3><p>One of the most frequently asked questions about jQuery is to Get or Set values of HTML Form elements. The jQuery val() method lets you ...</p></div></li></ul></div>]]></content:encoded>
			<wfw:commentRss>http://www.bageshsingh.com/bagesh-blog/2011/08/textbox-to-accept-only-numbers-digits-using-jquery-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Ip address validation in PHP using regular expression</title>
		<link>http://www.bageshsingh.com/bagesh-blog/2011/08/ip-address-validation-in-php-using-regular-expression/</link>
		<comments>http://www.bageshsingh.com/bagesh-blog/2011/08/ip-address-validation-in-php-using-regular-expression/#comments</comments>
		<pubDate>Mon, 29 Aug 2011 17:44:47 +0000</pubDate>
		<dc:creator>Bagesh Singh</dc:creator>
				<category><![CDATA[Home]]></category>
		<category><![CDATA[how-to]]></category>
		<category><![CDATA[Interview Question]]></category>
		<category><![CDATA[Others]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[Php interview question]]></category>
		<category><![CDATA[tips and technique]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://www.bageshsingh.com/bagesh-blog/?p=1461</guid>
		<description><![CDATA[If you don’t know how to validate the IP address format in PHP, then you are in the right place.I’ll show you here how to validate the IP address using regular expression in PHP. &#160; As you guyz know, IP address consists four parts. Each parts separated by period “.” and these part consists the [...]]]></description>
			<content:encoded><![CDATA[<p>If you don’t know how to validate the IP address format in PHP, then you are in the right place.I’ll show you here how to validate the IP address using regular expression in PHP.</p>
<p>&nbsp;</p>
<p>As you guyz know, IP address consists four parts. Each parts separated by period “.” and these part consists the digits which ranges from 0 to 255.</p>
<p><strong>Function to validate IP address in PHP using Regular Expression </strong></p>
<pre>//function to validate ip address format in php by Roshan Bhattarai(http://roshanbh.com.np)
function validateIpAddress($ip_addr)
{
  //first of all the format of the ip address is matched
  if(preg_match("/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/",$ip_addr))
  {
    //now all the intger values are separated
    $parts=explode(".",$ip_addr);
    //now we need to check each part can range from 0-255
    foreach($parts as $ip_parts)
    {
      if(intval($ip_parts)&gt;255 || intval($ip_parts)&lt;0)
      return false; //if number is not within range of 0-255
    }
    return true;
  }
  else
    return false; //if format of ip address doesn't matches
}</pre>
<p>As you can see above, first of all the format of the “$ip_addr” is validated using regular expression. In the regular expression “\d{1,3}” means that there should be digits which can be either 1 to 3 digits because a IP Adress can be “222.0.123.12″ or<br />
“12.15.123.5″. So, each part can consists 1 to 3 digits.</p>
<p>After validating the format using regular expression, each part of the IP address is separated using period(“.”) using explode() function available in PHP. And finally, it is checked that each part of the IP address is between 0 to 225 or not.</p>
<div id="seo_alrp_related"><h2>Posts Related to Ip address validation in PHP using regular expression</h2><ul><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/08/how-to-do-date-format-validation-in-php/" rel="bookmark">How to do Date format validation in PHP</a></h3><p>Today Sushil asked me how can we validate the date which is entered from textbox in “YYYY-MM-DD” format. Well, we can validate the format of ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/08/usa%e2%80%99s-zip-code-validation-in-php/" rel="bookmark">USA’s Zip Code Validation in PHP</a></h3><p>My friend Sushil was trying to write the regular expression for validating the format of the zip code of USA. After spending few minutes, I ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/08/understanding-and-validating-integers-in-php/" rel="bookmark">Understanding and Validating Integers in PHP</a></h3><p>I’ve found many of my friends struggling with the validation of integers i.e. the numbers with only digits in PHP. Some of them were wondering ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/08/canada%e2%80%99s-postal-code-validation-in-php/" rel="bookmark">Canada’s postal code validation in PHP</a></h3><p>Few days back, My friend Narendra asked me how to validate the postal code of Canada which is entered through the text box.And, I came ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/02/validate-ip-address-using-jquery/" rel="bookmark">Validate IP Address using jQuery</a></h3><p>I had recently posted on Add a Custom Validation Method to the jQuery Validation Plugin. A user asked me over twitter asking how to validate ...</p></div></li></ul></div>]]></content:encoded>
			<wfw:commentRss>http://www.bageshsingh.com/bagesh-blog/2011/08/ip-address-validation-in-php-using-regular-expression/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to do Date format validation in PHP</title>
		<link>http://www.bageshsingh.com/bagesh-blog/2011/08/how-to-do-date-format-validation-in-php/</link>
		<comments>http://www.bageshsingh.com/bagesh-blog/2011/08/how-to-do-date-format-validation-in-php/#comments</comments>
		<pubDate>Mon, 29 Aug 2011 17:43:58 +0000</pubDate>
		<dc:creator>Bagesh Singh</dc:creator>
				<category><![CDATA[how-to]]></category>
		<category><![CDATA[Interview Question]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[Javascript Interview Questions]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[Php interview question]]></category>
		<category><![CDATA[tips and technique]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://www.bageshsingh.com/bagesh-blog/?p=1459</guid>
		<description><![CDATA[Today Sushil asked me how can we validate the date which is entered from textbox in “YYYY-MM-DD” format. Well, we can validate the format of the date using regular expression but how to validate weather that date is valid date or not, such as “2007-02-29″ is the correct format of the date but it’s not [...]]]></description>
			<content:encoded><![CDATA[<p>Today Sushil asked me how can we validate the date which is entered from textbox in “YYYY-MM-DD” format. Well, we can validate the format of the date using regular expression but how to validate weather that date is valid date or not, such as “2007-02-29″ is the correct format of the date but it’s not the valid date.</p>
<p>&nbsp;</p>
<p>To overcome that situation, I’ve used checkdate() function available in PHP for validation of date.</p>
<h4>Function to validate date format in PHP</h4>
<pre>function checkDateFormat($date)
{
  //match the format of the date
  if (preg_match ("/^([0-9]{4})-([0-9]{2})-([0-9]{2})$/", $date, $parts))
  {
    //check weather the date is valid of not
        if(checkdate($parts[2],$parts[3],$parts[1]))
          return true;
        else
         return false;
  }
  else
    return false;
}</pre>
<p>In the above function, first of all format of date is validated using regular expression. As you can see the in the preg_match() function, there are three expression each separated by “-” and there can be only digits of length of 4,2 and 2 in these expressions. If the date format is incorrect then this function returns “false” value. And, if the supplied string contains the valid date format then the part matching each expression are stored in the “$parts” array. Such as, if we supply “2007-03-12″ then “2007″, “03″ and “12″ are stored in the “$parts” array. After that, checkdate() function of PHP is used check weather the supplied date is valid date or not.</p>
<h4>Example</h4>
<pre>echo checkDateFormat("2008-02-29"); //return true
echo checkDateFormat("2007-02-29"); //return false</pre>
<div id="seo_alrp_related"><h2>Posts Related to How to do Date format validation in PHP</h2><ul><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/05/php-date-functions-list/" rel="bookmark">PHP Date Functions List</a></h3><p>checkdate — Validate a gregorian date date — Format a local time/date getdate — Get date/time information gettimeofday — Get current time gmdate — Format ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/08/ip-address-validation-in-php-using-regular-expression/" rel="bookmark">Ip address validation in PHP using regular expression</a></h3><p>If you don’t know how to validate the IP address format in PHP, then you are in the right place.I’ll show you here how to ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2010/11/jquery-ui-datepicker-disable-specified-days/" rel="bookmark">jQuery UI DatePicker: Disable Specified Days</a></h3><p>One project I'm currently working on requires jQuery. The project also features a datepicker for requesting a visit to their location. jQuery UI's DatePicker plugin ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/08/usa%e2%80%99s-zip-code-validation-in-php/" rel="bookmark">USA’s Zip Code Validation in PHP</a></h3><p>My friend Sushil was trying to write the regular expression for validating the format of the zip code of USA. After spending few minutes, I ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/02/jquery-datepicker-%e2%80%93-select-a-date-programmatically/" rel="bookmark">jQuery DatePicker – Select a Date Programmatically</a></h3><p>I have seen users asking how to programmatically select a date using jQuery UI DatePicker control. The DatePicker beforeShowDay event is ideal for this type ...</p></div></li></ul></div>]]></content:encoded>
			<wfw:commentRss>http://www.bageshsingh.com/bagesh-blog/2011/08/how-to-do-date-format-validation-in-php/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Understanding and Validating Integers in PHP</title>
		<link>http://www.bageshsingh.com/bagesh-blog/2011/08/understanding-and-validating-integers-in-php/</link>
		<comments>http://www.bageshsingh.com/bagesh-blog/2011/08/understanding-and-validating-integers-in-php/#comments</comments>
		<pubDate>Mon, 29 Aug 2011 17:42:57 +0000</pubDate>
		<dc:creator>Bagesh Singh</dc:creator>
				<category><![CDATA[Home]]></category>
		<category><![CDATA[how-to]]></category>
		<category><![CDATA[Interview Question]]></category>
		<category><![CDATA[Others]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[Php interview question]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://www.bageshsingh.com/bagesh-blog/?p=1457</guid>
		<description><![CDATA[I’ve found many of my friends struggling with the validation of integers i.e. the numbers with only digits in PHP. Some of them were wondering why is_int() or is_integer() functions of PHP sometimes works and sometimes won’t. &#160; If you become clear with the concept of integer and string in PHP then you’ll obviously come [...]]]></description>
			<content:encoded><![CDATA[<p>I’ve found many of my friends struggling with the validation of integers i.e. the numbers with only digits in PHP. Some of them were wondering why is_int() or is_integer() functions of PHP sometimes works and sometimes won’t.</p>
<p>&nbsp;</p>
<p>If you become clear with the concept of integer and string in PHP then you’ll obviously come to know that why those functions are not working sometime to validate integers in PHP. Let’s look at this by an example</p>
<pre>$a='10';
$b=10;</pre>
<p>As you can see above, $a is string and $b is a integer and thats what does matter in PHP. Now, let’s try is_int() to validate the integers in PHP.</p>
<pre>echo is_int($a); //returns false
echo is_int($b); //return true</pre>
<p>And many of the PHP programmers tries to validate the posted values such as is_int($_POST['quantity']) and it just returns the false values although there are only digits in posted quantity.Why it is so? Because, $_POST['quantity'] is just a string and nothing more than a string. Values posted from the form’s element can’t be other variable type than string.</p>
<h4>How to validate integers (digits) in PHP?</h4>
<p>We can use regular expression to check weather posted value contains the integers only or not. But the regular expression might be a tedious task for people who are not good in using regular expression.</p>
<p>The best solution is using a function called <strong>ctype_digit()</strong> available in PHP. It just check weather the strings contains only digits or not. If you try using ctype_digit($_POST['quantity']) then It will just give you the desired result. But one thing you keep in mind that “ctype_digit()” is character type function the supplied parameter must be a string to get the proper result. And you can use “strval()” function available in PHP to convert any other data type to string in PHP</p>
<div id="seo_alrp_related"><h2>Posts Related to Understanding and Validating Integers in PHP</h2><ul><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/08/how-to-do-date-format-validation-in-php/" rel="bookmark">How to do Date format validation in PHP</a></h3><p>Today Sushil asked me how can we validate the date which is entered from textbox in “YYYY-MM-DD” format. Well, we can validate the format of ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/08/ip-address-validation-in-php-using-regular-expression/" rel="bookmark">Ip address validation in PHP using regular expression</a></h3><p>If you don’t know how to validate the IP address format in PHP, then you are in the right place.I’ll show you here how to ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/05/php-regular-expression-regex-functions-list/" rel="bookmark">PHP Regular Expression (Regex) Functions List</a></h3><p>Perl-Compatible Functions List preg_grep — Return array entries that match the pattern preg_match_all — Perform a global regular expression match preg_match — Perform a regular ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/08/usa%e2%80%99s-zip-code-validation-in-php/" rel="bookmark">USA’s Zip Code Validation in PHP</a></h3><p>My friend Sushil was trying to write the regular expression for validating the format of the zip code of USA. After spending few minutes, I ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/08/canada%e2%80%99s-postal-code-validation-in-php/" rel="bookmark">Canada’s postal code validation in PHP</a></h3><p>Few days back, My friend Narendra asked me how to validate the postal code of Canada which is entered through the text box.And, I came ...</p></div></li></ul></div>]]></content:encoded>
			<wfw:commentRss>http://www.bageshsingh.com/bagesh-blog/2011/08/understanding-and-validating-integers-in-php/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to disable the Enter key on HTML form</title>
		<link>http://www.bageshsingh.com/bagesh-blog/2011/08/how-to-disable-the-enter-key-on-html-form/</link>
		<comments>http://www.bageshsingh.com/bagesh-blog/2011/08/how-to-disable-the-enter-key-on-html-form/#comments</comments>
		<pubDate>Mon, 29 Aug 2011 17:36:08 +0000</pubDate>
		<dc:creator>Bagesh Singh</dc:creator>
				<category><![CDATA[Home]]></category>
		<category><![CDATA[how-to]]></category>
		<category><![CDATA[Interview Question]]></category>
		<category><![CDATA[Javascript Interview Questions]]></category>
		<category><![CDATA[Others]]></category>
		<category><![CDATA[tips and technique]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://www.bageshsingh.com/bagesh-blog/?p=1453</guid>
		<description><![CDATA[Normally when you have a form with several text input fields, it is undesirable that the form gets submitted when the user hits ENTER in a field. Some people are pressing the enter key instead of the tab key to get to the next field. They often do that by accident or because they are [...]]]></description>
			<content:encoded><![CDATA[<p>Normally when you have a form with several text input fields, it is undesirable that the form gets submitted when the user hits ENTER in a field. Some people are pressing the enter key instead of the tab key to get to the next field. They often do that by accident or because they are accustomed to terminate field input that way. If a browser regards hitting ENTER in a text input field as a request to submit the form immediately, there is no sure way to prevent that.</p>
<p>Add the below script to the &lt;head&gt; section of your page. The following code disables the enter key so that visitors of your web page can only use the tab key to get to the next field.</p>
<div>&lt;script type=&#8221;text/javascript&#8221;&gt;</p>
<p>function stopRKey(evt) {<br />
var evt = (evt) ? evt : ((event) ? event : null);<br />
var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);<br />
if ((evt.keyCode == 13) &amp;&amp; (node.type==&#8221;text&#8221;))  {return false;}<br />
}</p>
<p>document.onkeypress = stopRKey;</p>
<p>&lt;/script&gt;</p></div>
<div id="seo_alrp_related"><h2>Posts Related to How to disable the Enter key on HTML form</h2><ul><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/02/add-a-custom-validation-method-to-the-jquery-validation-plugin/" rel="bookmark">Add a Custom Validation Method to the jQuery Validation Plugin</a></h3><p>When it comes to Validation using jQuery, the jQuery Validation Plugin is my obvious choice. This plugin provides you with a number of pre-built validation ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/02/validate-ip-address-using-jquery/" rel="bookmark">Validate IP Address using jQuery</a></h3><p>I had recently posted on Add a Custom Validation Method to the jQuery Validation Plugin. A user asked me over twitter asking how to validate ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2010/11/adding-custom-javascript-on-admin-form-in-magento-backend-2/" rel="bookmark">Adding Custom Javascript on Admin form in Magento (Backend)</a></h3><p>Sometimes in Magento, while creating a custom module we need to add our custom Javascript code in our Admin form. These Admin forms we create ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2010/09/paypal-code-in-php-quick-e-commerce-with-php-and-paypal/" rel="bookmark">Paypal code in php : Quick E-Commerce with  PHP and PayPal</a></h3><p>Hard-Coded Information A number of the parameters needed by PayPal can be hard-coded right into your page. For example, the "action" attribute of the "form" ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2010/10/adding-custom-javascript-on-admin-form-in-magento-backend/" rel="bookmark">Adding Custom Javascript on Admin form in Magento (Backend)</a></h3><p>Sometimes in Magento, while creating a custom module we need to add our custom Javascript code in our Admin form. These Admin forms we create ...</p></div></li></ul></div>]]></content:encoded>
			<wfw:commentRss>http://www.bageshsingh.com/bagesh-blog/2011/08/how-to-disable-the-enter-key-on-html-form/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to install and configure PHP 5 on Windows box</title>
		<link>http://www.bageshsingh.com/bagesh-blog/2011/08/ow-to-install-and-configure-php-5-on-windows-box/</link>
		<comments>http://www.bageshsingh.com/bagesh-blog/2011/08/ow-to-install-and-configure-php-5-on-windows-box/#comments</comments>
		<pubDate>Mon, 29 Aug 2011 17:32:24 +0000</pubDate>
		<dc:creator>Bagesh Singh</dc:creator>
				<category><![CDATA[Home]]></category>
		<category><![CDATA[how-to]]></category>
		<category><![CDATA[Interview Question]]></category>
		<category><![CDATA[mysql]]></category>
		<category><![CDATA[mysql interview question]]></category>
		<category><![CDATA[Others]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[Php interview question]]></category>
		<category><![CDATA[tips and technique]]></category>
		<category><![CDATA[Tools]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[Configure Apache Web Server]]></category>
		<category><![CDATA[Configure IIS]]></category>
		<category><![CDATA[Create a session state directory and point the session.save_path variable in php.ini to it]]></category>
		<category><![CDATA[Date Setting]]></category>
		<category><![CDATA[Download and unzip the latest version of PHP]]></category>
		<category><![CDATA[Location of libmysql.dll]]></category>
		<category><![CDATA[Make sure that PHP folder is in the system path]]></category>
		<category><![CDATA[Rename/copy php.ini-recommended to php.ini]]></category>
		<category><![CDATA[Setup the PHP extensions]]></category>
		<category><![CDATA[Test your setup]]></category>

		<guid isPermaLink="false">http://www.bageshsingh.com/bagesh-blog/?p=1449</guid>
		<description><![CDATA[It is assumed that you have already successfully setup IIS or installed Apache on your machine and configured it. So, to configure PHP and secure its correct operation you need to go through a couple of steps. Download and unzip the latest version of PHP Rename/copy php.ini-recommended to php.ini Create a session state directory and [...]]]></description>
			<content:encoded><![CDATA[<p>It is assumed that you have already successfully setup IIS or installed Apache on your machine and configured it. So, to configure PHP and secure its correct operation you need to go through a couple of steps.</p>
<ul>
<li>Download and unzip the latest version of PHP</li>
<li>Rename/copy php.ini-recommended to php.ini</li>
<li>Create a session state directory and point the session.save_path variable in php.ini to it</li>
<li>Setup the PHP extensions</li>
<li>Make sure that PHP folder is in the system path</li>
<li>Configure IIS</li>
<li>Configure Apache Web Server</li>
<li>Test your setup</li>
<li>Date Setting</li>
<li>Location of libmysql.dll</li>
</ul>
<p><a name="download"></a>Download and unzip the latest version of PHP</p>
<p>Download the latest zipped distribution of PHP from http://php.net. Unzip it. The recommendation is to put all the PHP stuff in a folder just off of the root drive (avoid whitespace), like C:\PHP.</p>
<p><a name="rename"></a>Rename/copy php.ini-recommended to php.ini</p>
<p>In your PHP directory, you&#8217;ll find a couple of php.ini-* files. They are pre-configured settings for a PHP install that you can use as an initial setup. The php.ini-recommended is the most secure, hence, the recommended one; just rename it to php.ini and copy to your Windows directory.</p>
<p><a name="create"></a>Create a session state directory and point the session.save_path variable in php.ini to it</p>
<p>This is optional, but recommended step. PHP does not need sessions, but it&#8217;s something that will most likely be useful.</p>
<p>Create a session directory somewhere on the server. I created C:\PHP\sessionFolder. This directory will hold many small files with session variable information for PHP.</p>
<p>Now change the value of the session.save_path variable in php.ini to be the full path to that directory (session.save_path=C:\PHP\sessionFolder).</p>
<p><img src="http://www.webcheatsheet.com/PHP/images/install_and_configure_1.gif" alt="" width="533" height="290" border="0" /></p>
<p><a name="extsetup"></a>Setup the PHP extensions</p>
<p>You need to point PHP to the directory that holds the extension libraries and you need to uncomment the desired extensions.</p>
<ul>
<li>Point PHP to the correct directory:<br />
Set extension_dir in php.ini to &#8220;C:\PHP\ext&#8221; (extension_dir = &#8220;C:\PHP\ext&#8221;)</li>
<li>Uncomment the ones you want to use.<br />
It’s important to be sure that php_mysql.dll extension is uncommented (for PHP 5 or newer).</li>
</ul>
<p><img src="http://www.webcheatsheet.com/PHP/images/install_and_configure_2.gif" alt="" width="533" height="509" border="0" /></p>
<p><img src="http://www.webcheatsheet.com/PHP/images/install_and_configure_3.gif" alt="" width="533" height="288" border="0" /></p>
<p><a name="systempath"></a>Make sure that PHP folder is in the system path</p>
<p>You should add &#8220;C:\PHP&#8221; to the server&#8217;s PATH environment variable:</p>
<ul>
<li>Right-click on My Computer, choose Properties</li>
<li>Flip to the Advanced tab</li>
<li>Click the Environment Variables button</li>
<li>Double-click the Path variable in the list of System variables.</li>
<li>Either add &#8220;C:\PHP;&#8221; to the beginning or &#8220;;C:\PHP&#8221; to the end (sans quotes, not both).</li>
<li>Restart IIS for it to take effect.</li>
</ul>
<p>(To restart IIS you should right-click the local computer in the left pane of IIS Manager, click on All Tasks -&gt; Restart IIS&#8230; -&gt; OK)</p>
<p>Instead, you can copy all non-php dll files from C:\PHP to C:\Windows\System32 (or somewhere else in the server&#8217;s PATH), but the first is the preferred method since it keeps the installation in one place, making upgrading or uninstalling easier.</p>
<p><img src="http://www.webcheatsheet.com/PHP/images/install_and_configure_4.gif" alt="" width="419" height="488" border="0" /></p>
<p><a name="iisconfig"></a> Configure IIS</p>
<p>For these steps, open IIS Manager<br />
(Start -&gt; Control Panel -&gt; Administrative Tools -&gt; Internet Information Services (IIS)  Manager).</p>
<p>Then add new extension (.php)</p>
<ul>
<li>Expand the local computer in the left pane</li>
<li>Right-click on &#8220;Web Sites&#8221; in the left pane, then click &#8220;Properties&#8221; in the menu that pops up</li>
<li>Flip top the Home Directory tab</li>
<li>Click &#8220;Configuration&#8221;</li>
<li>Flip to the Mappings tab</li>
<li>Click Add&#8230;</li>
<li>Enter the full path to php5isapi.dll in the &#8220;Executable&#8221; textbox (Browse&#8230; to find it more easily if you need to)</li>
<li>Enter &#8220;.php&#8221; in the Extension textbox</li>
<li>Select radial button Limit to, enter &#8220;GET,POST,HEAD&#8221;</li>
<li>Click OK all the way out</li>
</ul>
<p>This will apply to every website.</p>
<p>This sets up IIS to actually respond to requests for php files. Until now, IIS hadn&#8217;t known what to do with php files, you just told it to pass them through php5isapi.dll.</p>
<p><a name="apacheconfig"></a>Configure Apache Web Server</p>
<p>If you want PHP to work with your Apache server, you will need to modify your Apache configuration file to load it. There are two ways to configure Apache to use PHP: one is to configure it to load the PHP interpreter as an Apache module. The other is to configure it to run the PHP interpreter as a CGI binary. Unless you have a particular reason for running PHP as a CGI binary, you will probably want to load PHP as a module in Apache, since it runs more efficiently that way.</p>
<p>To configure Apache to load PHP as a module to parse your PHP scripts you should make some changes in the Apache configuration file, &#8220;httpd.conf&#8221;, typically found in &#8220;c:\Program Files\Apache Group\Apache\conf\&#8221;. It also can be accessed from your program files menu.</p>
<ul>
<li>Search for the section that has a series of commented out &#8220;LoadModule&#8221; statements. Add the following line after all the LoadModule statements:<br />
<em>LoadModule php5_module &#8220;c:/php/php5apache2.dll&#8221;</em></li>
<li>Search for &#8220;AddType&#8221; and add the following line after the last &#8220;AddType&#8221; statement:<br />
<em>AddType application/x-httpd-php .php </em></li>
</ul>
<p>If you need to support other file types, like &#8220;.php3&#8243; and &#8220;.phtml&#8221;, simply add them to the list, like this:<br />
<em>AddType application/x-httpd-php .php3<br />
AddType application/x-httpd-php .phtml</em></p>
<p><a name="test"></a>Test your setup</p>
<p>Create a new file named test.php in one of the websites. Expand the Web Sites folder in the left pane of IIS Manager to see a list of existing websites. Right-click on a website -&gt; Properties -&gt; Home Directory -&gt; Local Path will show you where the website root directory is.</p>
<p>Create test.php file with the following line: &lt;?php phpinfo(); ?&gt;</p>
<p>With your browser go to <span style="color: #000099;">http://localhost/test.php</span></p>
<p>After loading test.php, you should see some information about your PHP installation. Be sure to scroll all the way down to the bottom to see that there were no errors. Pay attention to &#8220;Configuration File (php.ini) Path&#8221; field. Field&#8217;s value is current location of php.ini file and you should make appropriate changes in it.</p>
<p><a name="datesettings"></a>Date Settings (for PHP 5.1 or newer)</p>
<p>It is strongly recommended to configure date settings in php.ini. It is not safe to rely on the system&#8217;s time zone settings.</p>
<p>Set date.timezone in php.ini to your time zone (in my example it&#8217;s Europe/Moscow).</p>
<p>Complete list of Timezones you can see at http://php.net/manual/en/timezones.php</p>
<p><img src="http://www.webcheatsheet.com/PHP/images/install_and_configure_5.gif" alt="" width="533" height="288" border="0" /></p>
<p><a name="location"></a>Location of libmysql.dll</p>
<p>Lastly, we need to be sure that copy of libmysql.dll is located in PHP folder (for PHP 5.0 or newer).</p>
<div id="seo_alrp_related"><h2>Posts Related to How to install and configure PHP 5 on Windows box</h2><ul><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2010/05/how-do-you-install-an-extension-in-joomla/" rel="bookmark">How do you install an extension in joomla?</a></h3><p>Before starting it always is wise to read the documentation associated with an extension. Most extensions have homepages and forums, and it is a good ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2010/11/check-enable-mod_rewrite-apache/" rel="bookmark">How to check and enable mod_rewrite module in apache</a></h3><p>I’ve got around 15 emails asking from readers, how to check the mod_rewrite module in apache and enable mod_rewrite module in apache after reading two ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2010/03/php-installation-how-to-install-php/" rel="bookmark">PHP Installation : How to install php</a></h3><p>PHP Installation Requirement: PHP 5.1.2 Apache 2.0.55 Java Bridge 3.0.7a Default setting: D:/payment Steps: 1. Install apache in d:/payment/ It automatically create folder named apache2 ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/08/how-to-create-thumbnail-images-using-php/" rel="bookmark">How to Create Thumbnail Images using PHP</a></h3><p>Download Source This tutorial will describe how to create thumbnail images on the fly using PHP. Furthermore you will learn how to process a whole ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/05/php-ftp-functions-list/" rel="bookmark">PHP FTP Functions List</a></h3><p>ftp_cdup — Changes to the parent directory ftp_chdir — Changes directories on a FTP server ftp_close — Closes an FTP connection ftp_connect — Opens an ...</p></div></li></ul></div>]]></content:encoded>
			<wfw:commentRss>http://www.bageshsingh.com/bagesh-blog/2011/08/ow-to-install-and-configure-php-5-on-windows-box/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to Send Email (Text/HTML/Attachments) in php</title>
		<link>http://www.bageshsingh.com/bagesh-blog/2011/08/how-to-send-email-texthtmlattachments-in-php/</link>
		<comments>http://www.bageshsingh.com/bagesh-blog/2011/08/how-to-send-email-texthtmlattachments-in-php/#comments</comments>
		<pubDate>Mon, 29 Aug 2011 17:30:19 +0000</pubDate>
		<dc:creator>Bagesh Singh</dc:creator>
				<category><![CDATA[Home]]></category>
		<category><![CDATA[how-to]]></category>
		<category><![CDATA[Interview Question]]></category>
		<category><![CDATA[Others]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[Php interview question]]></category>
		<category><![CDATA[tips and technique]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[ATTACHMENT]]></category>
		<category><![CDATA[DUAL]]></category>
		<category><![CDATA[EMAIL]]></category>
		<category><![CDATA[FORMAT]]></category>
		<category><![CDATA[HTML]]></category>
		<category><![CDATA[SEND]]></category>
		<category><![CDATA[Sending a Simple Text Email in php]]></category>
		<category><![CDATA[Sending Email with Attachments in php]]></category>
		<category><![CDATA[Sending HTML Email in php]]></category>
		<category><![CDATA[server]]></category>
		<category><![CDATA[SMTP]]></category>
		<category><![CDATA[text]]></category>

		<guid isPermaLink="false">http://www.bageshsingh.com/bagesh-blog/?p=1447</guid>
		<description><![CDATA[Email is the most popular Internet service today. A plenty of emails are sent and delivered each day. The goal of this tutorial is to demonstrate how to generate and send emails in PHP. So, you want to send automated email messages from your PHP application. This can be in direct response to a user&#8217;s [...]]]></description>
			<content:encoded><![CDATA[<p>Email is the most popular Internet service today. A plenty of emails are sent and delivered each day. The goal of this tutorial is to demonstrate how to generate and send emails in PHP.</p>
<p>So, you want to send automated email messages from your PHP application. This can be in direct response to a user&#8217;s action, such as signing up for your site, or a recurring event at a set time, such as a monthly newsletter. Sometimes email contains file attachments, both plain text and HTML portions, and so on. To understand how to send each variation that may exist on an email, we will start with the simple example and move to the more complicated.</p>
<ul>
<li>Sending a Simple Text Email</li>
<li>Sending HTML Email</li>
<li>Sending Email with Attachments</li>
</ul>
<p>Note that to send email with PHP you need a working email server that you have permission to use: for Unix machines, this is often Sendmail; for Windows machines, you must set the SMTP directive in your <em>php.ini</em> file to point to your email server.</p>
<p><a name="text"></a>Sending a Simple Text Email<a name="form"></a></p>
<p>At first let&#8217;s consider how to send a simple text email messages. PHP includes the <em>mail()</em> function for sending email, which takes three basic and two optional parameters. These parameters are, in order, the email address to send to, the subject of the email, the message to be sent, additional headers you want to include and finally an additional parameter to the Sendmail program. The <em>mail()</em> function returns True if the message is sent successfully and False otherwise. Have a look at the example:</p>
<div>&lt;?php<br />
//define the receiver of the email<br />
$to = &#8216;youraddress@example.com&#8217;;<br />
//define the subject of the email<br />
$subject = &#8216;Test email&#8217;;<br />
//define the message to be sent. Each line should be separated with \n<br />
$message = &#8220;Hello World!\n\nThis is my first mail.&#8221;;<br />
//define the headers we want passed. Note that they are separated with \r\n<br />
$headers = &#8220;From: webmaster@example.com\r\nReply-To: webmaster@example.com&#8221;;<br />
//send the email<br />
$mail_sent = @mail( $to, $subject, $message, $headers );<br />
//if the message is sent successfully print &#8220;Mail sent&#8221;. Otherwise print &#8220;Mail failed&#8221;<br />
echo $mail_sent ? &#8220;Mail sent&#8221; : &#8220;Mail failed&#8221;;<br />
?&gt;</div>
<p>As you can see, it very easy to send an email. You can add more receivers by either adding their addresses, comma separated, to the $to variable, or by adding cc: or bcc: headers. If you don&#8217;t receive the test mail, you have probably installed PHP incorrectly, or may not have permission to send emails.</p>
<p><img src="http://www.webcheatsheet.com/images/uparrow.gif" alt="" width="10" height="10" border="0" /><span style="color: #999999; font-size: x-small;">Back to top</span></p>
<p><a name="html"></a>Sending HTML Email<a name="code"></a></p>
<p>The next step is to examine how to send HTML email. However, some mail clients cannot understand HTML emails. Therefore it is best to send any HTML email using a multipart construction, where one part contains a plain-text version of the email and the other part is HTML. If your customers have HTML email turned off, they will still get a nice email, even if they don&#8217;t get all of the HTML markup. Have a look at the example:</p>
<div>&lt;?php<br />
//define the receiver of the email<br />
$to = &#8216;youraddress@example.com&#8217;;<br />
//define the subject of the email<br />
$subject = &#8216;Test HTML email&#8217;;<br />
//create a boundary string. It must be unique<br />
//so we use the MD5 algorithm to generate a random hash<br />
$random_hash = md5(date(&#8216;r&#8217;, time()));<br />
//define the headers we want passed. Note that they are separated with \r\n<br />
$headers = &#8220;From: webmaster@example.com\r\nReply-To: webmaster@example.com&#8221;;<br />
//add boundary string and mime type specification<br />
$headers .= &#8221;\r\nContent-Type: multipart/alternative; boundary=\&#8221;PHP-alt-&#8221;.$random_hash.&#8221;\&#8221;";<br />
//define the body of the message.<br />
ob_start(); <span style="color: #007700;">//Turn on output buffering</span><br />
?&gt;<br />
&#8211;PHP-alt-&lt;?php echo $random_hash; ?&gt;<br />
Content-Type: text/plain; charset=&#8221;iso-8859-1&#8243;<br />
Content-Transfer-Encoding: 7bit</p>
<p>Hello World!!!<br />
This is simple text email message.</p>
<p>&#8211;PHP-alt-&lt;?php echo $random_hash; ?&gt;<br />
Content-Type: text/html; charset=&#8221;iso-8859-1&#8243;<br />
Content-Transfer-Encoding: 7bit</p>
<p>&lt;h2&gt;Hello World!&lt;/h2&gt;<br />
&lt;p&gt;This is something with &lt;b&gt;HTML&lt;/b&gt; formatting.&lt;/p&gt;</p>
<p>&#8211;PHP-alt-&lt;?php echo $random_hash; ?&gt;&#8211;<br />
&lt;?<br />
//copy current buffer contents into $message variable and delete current output buffer<br />
$message = ob_get_clean();<br />
//send the email<br />
$mail_sent = @mail( $to, $subject, $message, $headers );<br />
//if the message is sent successfully print &#8220;Mail sent&#8221;. Otherwise print &#8220;Mail failed&#8221;<br />
echo $mail_sent ? &#8220;Mail sent&#8221; : &#8220;Mail failed&#8221;;<br />
?&gt;</p></div>
<p>In the preceding example we add one additional header of Content-type:multipart/alternative and boundary string that marks the different areas of the email. Note that the content type of the message itself is sent as a mail header, while the content types of the individual parts of the message are embedded in the message itself. This way, mail clients can decide which part of the message they want to display.</p>
<p>Sending Email with Attachment<a name="attachment"></a></p>
<p>The last variation that we will consider is email with attachments. To send an email with attachment we need to use the multipart/mixed MIME type that specifies that mixed types will be included in the email. Moreover, we want to use multipart/alternative MIME type to send both plain-text and HTML version of the email. Have a look at the example:</p>
<div>&lt;?php<br />
//define the receiver of the email<br />
$to = &#8216;youraddress@example.com&#8217;;<br />
//define the subject of the email<br />
$subject = &#8216;Test email with attachment&#8217;;<br />
//create a boundary string. It must be unique<br />
//so we use the MD5 algorithm to generate a random hash<br />
$random_hash = md5(date(&#8216;r&#8217;, time()));<br />
//define the headers we want passed. Note that they are separated with \r\n<br />
$headers = &#8220;From: webmaster@example.com\r\nReply-To: webmaster@example.com&#8221;;<br />
//add boundary string and mime type specification<br />
$headers .= &#8220;\r\nContent-Type: multipart/mixed; boundary=\&#8221;PHP-mixed-&#8221;.$random_hash.&#8221;\&#8221;";<br />
//read the atachment file contents into a string,<br />
//encode it with MIME base64,<br />
//and split it into smaller chunks<br />
$attachment = chunk_split(base64_encode(file_get_contents(&#8216;attachment.zip&#8217;)));<br />
//define the body of the message.<br />
ob_start(); //Turn on output buffering<br />
?&gt;<br />
&#8211;PHP-mixed-&lt;?php echo $random_hash; ?&gt;<br />
Content-Type: multipart/alternative; boundary=&#8221;PHP-alt-&lt;?php echo $random_hash; ?&gt;&#8221;</p>
<p>&#8211;PHP-alt-&lt;?php echo $random_hash; ?&gt;<br />
Content-Type: text/plain; charset=&#8221;iso-8859-1&#8243;<br />
Content-Transfer-Encoding: 7bit</p>
<p>Hello World!!!<br />
This is simple text email message.</p>
<p>&#8211;PHP-alt-&lt;?php echo $random_hash; ?&gt;<br />
Content-Type: text/html; charset=&#8221;iso-8859-1&#8243;<br />
Content-Transfer-Encoding: 7bit</p>
<p>&lt;h2&gt;Hello World!&lt;/h2&gt;<br />
&lt;p&gt;This is something with &lt;b&gt;HTML&lt;/b&gt; formatting.&lt;/p&gt;</p>
<p>&#8211;PHP-alt-&lt;?php echo $random_hash; ?&gt;&#8211;</p>
<p>&#8211;PHP-mixed-&lt;?php echo $random_hash; ?&gt;<br />
Content-Type: application/zip; name=&#8221;attachment.zip&#8221;<br />
Content-Transfer-Encoding: base64<br />
Content-Disposition: attachment</p>
<p>&lt;?php echo $attachment; ?&gt;<br />
&#8211;PHP-mixed-&lt;?php echo $random_hash; ?&gt;&#8211;</p>
<p>&lt;?php<br />
//copy current buffer contents into $message variable and delete current output buffer<br />
$message = ob_get_clean();<br />
//send the email<br />
$mail_sent = @mail( $to, $subject, $message, $headers );<br />
//if the message is sent successfully print &#8220;Mail sent&#8221;. Otherwise print &#8220;Mail failed&#8221;<br />
echo $mail_sent ? &#8220;Mail sent&#8221; : &#8220;Mail failed&#8221;;<br />
?&gt;</p></div>
<p>As you can see, sending an email with attachment is easy to accomplish. In the preceding example we have multipart/mixed MIME type, and inside it we have multipart/alternative MIME type that specifies two versions of the email. To include an attachment to our message, we read the data from the specified file into a string, encode it with base64,  split it in smaller chunks to make sure that it matches the MIME specifications and then include it as an attachment.</p>
<div id="seo_alrp_related"><h2>Posts Related to How to Send Email (Text/HTML/Attachments) in php</h2><ul><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2010/05/a-solution-for-e-mail-handling-in-cakephp/" rel="bookmark">A solution for e-mail handling in CakePHP</a></h3><p>The emailComponent (cake\libs\controller\components\email.php) is a way for you to using the same concepts of layouts and view ctp files to send formated messages as text, ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2010/04/newsletter-email-tracking-read-or-not/" rel="bookmark">Newsletter Email Tracking: Read or Not?</a></h3><p>I have completed first phase of a simple, yet useful Newsletter System. When I demonstrated to the clients, they came up with a question if ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2010/12/how-to-get-a-facebook-email-address-like-facebook-com/" rel="bookmark">How to Get a Facebook Email Address like @facebook.com?</a></h3><p>How to Get a Facebook Email Address like @facebook.com? Facebook as you know the top social networking site has recently introduced its own email service ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2010/12/facebook-unveils-email-addresses-new-messaging-features/" rel="bookmark">Facebook Unveils Email Addresses, New Messaging Features</a></h3><p>Facebook CEO Mark Zuckerberg announced that the social network will be launching a revamped messaging product, 'Messages,' that will give users an "@facebook.com" email address. ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2010/12/facebook-email-service-new-email-in-facebook/" rel="bookmark">Facebook Email Service : new email in facebook</a></h3><p>We have got news reports from many trusted sources that Facebook’s new email service called Project Titan is going to live on coming Monday. So ...</p></div></li></ul></div>]]></content:encoded>
			<wfw:commentRss>http://www.bageshsingh.com/bagesh-blog/2011/08/how-to-send-email-texthtmlattachments-in-php/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>how to work with Directories in php</title>
		<link>http://www.bageshsingh.com/bagesh-blog/2011/08/how-to-work-with-directories-in-php/</link>
		<comments>http://www.bageshsingh.com/bagesh-blog/2011/08/how-to-work-with-directories-in-php/#comments</comments>
		<pubDate>Mon, 29 Aug 2011 17:28:22 +0000</pubDate>
		<dc:creator>Bagesh Singh</dc:creator>
				<category><![CDATA[how-to]]></category>
		<category><![CDATA[Interview Question]]></category>
		<category><![CDATA[Others]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[Php interview question]]></category>
		<category><![CDATA[tips and technique]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[Creating New Directories]]></category>
		<category><![CDATA[Deleting the Directory and Its Contents]]></category>
		<category><![CDATA[DIRECTORIES]]></category>
		<category><![CDATA[FILES]]></category>
		<category><![CDATA[functions]]></category>
		<category><![CDATA[ITERATORS]]></category>
		<category><![CDATA[PHP5]]></category>
		<category><![CDATA[Reading the Contents of a Directory]]></category>
		<category><![CDATA[RECURSION]]></category>

		<guid isPermaLink="false">http://www.bageshsingh.com/bagesh-blog/?p=1445</guid>
		<description><![CDATA[As is necessary for any language, PHP has a complete set of directory support functions. PHP gives you a variety of functions to read and manipulate directories and directory entries. Like other file-related parts of PHP, the functions are similar to the C functions that accomplish the same tasks, with some simplifications. This tutorial describes [...]]]></description>
			<content:encoded><![CDATA[<p>As is necessary for any language, PHP has a complete set of directory support functions. PHP gives you a variety of functions to read and manipulate directories and directory entries. Like other file-related parts of PHP, the functions are similar to the C functions that accomplish the same tasks, with some simplifications. This tutorial describes how PHP handles directories. You will look at how to create, remove, and read them.</p>
<ul>
<li>Reading the Contents of a Directory</li>
<li>Deleting the Directory and Its Contents</li>
<li>Creating New Directories</li>
</ul>
<p><a name="read"></a>Reading the Contents of a Directory</p>
<p>Let&#8217;s start with simple listing the contents of a directory. We need three functions to perform this task: opendir(), readdir() and closedir(). The opendir() function takes one parameter, which is the directory we want to read, and returns a directory handle to be used in subsequent readdir() and closedir() calls. opendir() returns False if the directory could not be opened.</p>
<p>The readdir() function takes one parameter, which is the handle that opendir() returned and each time we call readdir() it returns the filename of the next file in the directory. readdir() returns False if the end of the directory has been reached. Note that readdir() returns only the names of its items, rather than full paths.</p>
<p>The example below creates a select box that lists all the files in a directory. Copy and paste this code and save it as <em>index.php</em> in a directory you wish do display all files for. It automatically excludes itself from the list, and is easy to modify to make it ignore other files as well:</p>
<div>&lt;?php<br />
// open the current directory<br />
$dhandle = opendir(&#8216;.&#8217;);<br />
// define an array to hold the files<br />
$files = array();</p>
<p>if ($dhandle) {<br />
// loop through all of the files<br />
while (false !== ($fname = readdir($dhandle))) {<br />
// if the file is not this file, and does not start with a &#8216;.&#8217; or &#8216;..&#8217;,<br />
// then store it for later display<br />
if (($fname != &#8216;.&#8217;) &amp;&amp; ($fname != &#8216;..&#8217;) &amp;&amp;<br />
($fname != basename($_SERVER['PHP_SELF']))) {<br />
// store the filename<br />
$files[] = (is_dir( &#8220;./$fname&#8221; )) ? &#8220;(Dir) {$fname}&#8221; : $fname;<br />
}<br />
}<br />
// close the directory<br />
closedir($dhandle);<br />
}</p>
<p>echo &#8220;&lt;select name=\&#8221;file\&#8221;&gt;\n&#8221;;<br />
// Now loop through the files, echoing out a new select option for each one<br />
foreach( $files as $fname )<br />
{<br />
echo &#8220;&lt;option&gt;{$fname}&lt;/option&gt;\n&#8221;;<br />
}<br />
echo &#8220;&lt;/select&gt;\n&#8221;;<br />
?&gt;</p></div>
<p>First, we open the directory for reading with the opendir() function and use a while statement to loop through each of its entries. We call readdir() as part of the while statement&#8217;s test expression, assigning its result to the $fname variable. We are explicitly testing whether the return value is equal to and of the same type as False since otherwise, any directory entry whose name evaluates to False will stop the loop prematurely. Within the body of the while statement, we check if the file is not this file, and does not start with a <strong>.</strong> (current directory) or <strong>..</strong> (parent directory) and then store the file name into the $files array. We also do one more check. If a full file path leads to a directory then we add to the file name &#8220;(Dir)&#8221;.</p>
<p>There is another way to iterate over all files in a directory. PHP 5 has a set of objects called iterators. Iterators help eliminate problems in your code. For instance, PHP 5 provides a DirectoryIterator:</p>
<div>&lt;?php<br />
echo &#8220;&lt;select name=\&#8221;file\&#8221;&gt;\n&#8221;;<br />
foreach (new DirectoryIterator(&#8216;.&#8217;) as $file) {<br />
// if the file is not this file, and does not start with a &#8216;.&#8217; or &#8216;..&#8217;,<br />
// then store it for later display<br />
if ( (!$file-&gt;isDot()) &amp;&amp; ($file-&gt;getFilename() != basename($_SERVER['PHP_SELF'])) ) {<br />
echo &#8220;&lt;option&gt;&#8221;;<br />
// if the element is a directory add to the file name &#8220;(Dir)&#8221;<br />
echo ($file-&gt;isDir()) ? &#8220;(Dir) &#8220;.$file-&gt;getFilename() : $file-&gt;getFilename();<br />
echo &#8220;&lt;/option&gt;\n&#8221;;<br />
}<br />
}<br />
echo &#8220;&lt;/select&gt;\n&#8221;;<br />
?&gt;</div>
<p>This example produces the same results as the earlier code that uses the directory functions, but this code is shorter and safer because you cannot forget the !== = comparison.</p>
<p><img src="http://www.webcheatsheet.com/images/uparrow.gif" alt="" width="10" height="10" border="0" /><span style="color: #999999; font-size: x-small;">Back to top</span></p>
<p><a name="delete"></a>Deleting the Directory and Its Contents</p>
<p>PHP has the rmdir( ) function that takes a directory name as its only parameter and will remove the specified directory from the file system, if the process running your script has the right to do so. However, the rmdir() function works only on empty directories. The example below deletes empty directory named &#8220;temporary&#8221;:</p>
<div>&lt;?php<br />
rmdir( &#8220;temporary&#8221; );<br />
?&gt;</div>
<p>If you want to delete non-empty directory, you should use the recursion. In the following example we create recursive function named deleteDir() that takes a directory name as a parameter and will go through each subdirectory, deleting files as they go. When the directory is empty, we use rmdir() to remove it.</p>
<div>&lt;?php<br />
function deleteDir($dir) {<br />
// open the directory<br />
$dhandle = opendir($dir);</p>
<p>if ($dhandle) {<br />
<span style="color: #007700;">// loop through it</span><br />
while (false !== ($fname = readdir($dhandle))) {<br />
// if the element is a directory, and<br />
// does not start with a &#8216;.&#8217; or &#8216;..&#8217;<br />
// we call deleteDir function recursively<br />
// passing this element as a parameter<br />
if (is_dir( &#8220;{$dir}/{$fname}&#8221; )) {<br />
if (($fname != &#8216;.&#8217;) &amp;&amp; ($fname != &#8216;..&#8217;)) {<br />
echo &#8220;&lt;u&gt;Deleting Files in the Directory&lt;/u&gt;: {$dir}/{$fname} &lt;br /&gt;&#8221;;<br />
deleteDir(&#8220;$dir/$fname&#8221;);<br />
}<br />
<span style="color: #007700;">// the element is a file, so we delete it</span><br />
} else {<br />
echo &#8220;Deleting File: {$dir}/{$fname} &lt;br /&gt;&#8221;;<br />
unlink(&#8220;{$dir}/{$fname}&#8221;);<br />
}<br />
}<br />
closedir($dhandle);<br />
}<br />
<span style="color: #007700;">// now directory is empty, so we can use<br />
// the rmdir() function to delete it</span><br />
echo &#8220;&lt;u&gt;Deleting Directory&lt;/u&gt;: {$dir} &lt;br /&gt;&#8221;;<br />
rmdir($dir);<br />
}</p>
<p>// call deleteDir function and pass to it<br />
// as a parameter a directory name<br />
deleteDir(&#8220;temporary&#8221;);<br />
?&gt;</p></div>
<p>Another way to delete non-empty directory is to use RecursiveDirectoryIterator and RecursiveIteratorIterator. The RecursiveIteratorIterator must be told to provide children (files and subdirectories) before parents with its CHILD_FIRST constant. Have a look at the code:</p>
<div>&lt;?php<br />
function deleteDir($dir) {<br />
$iterator = new RecursiveDirectoryIterator($dir);<br />
foreach (new RecursiveIteratorIterator($iterator, RecursiveIteratorIterator::CHILD_FIRST) as $file)<br />
{<br />
if ($file-&gt;isDir()) {<br />
rmdir($file-&gt;getPathname());<br />
} else {<br />
unlink($file-&gt;getPathname());<br />
}<br />
}<br />
rmdir($dir);<br />
}</p>
<p>deleteDir(&#8220;temporary&#8221;);<br />
?&gt;</p></div>
<p>Note: The CHILD_FIRST constant was added with PHP 5.1</p>
<p><img src="http://www.webcheatsheet.com/images/uparrow.gif" alt="" width="10" height="10" border="0" /><span style="color: #999999; font-size: x-small;">Back to top</span></p>
<p><a name="create"></a>Creating New Directories</p>
<p>Creating new directories in PHP is accomplished using the mkdir() function, which takes two parameters. These parameters are, in order, a directory name you want to create and a permission mode for a new directory, which must be an octal number. The mode parameter is optional and has an effect only on Unix systems. Have a look at the example:</p>
<div>&lt;?php<br />
<span style="color: #007700;">// if /path/to/my exists, this should return true<br />
// if PHP has the right permissions</span><br />
mkdir(&#8220;/path/to/directory&#8221;, 0777);<br />
?&gt;</div>
<p>By default, the mkdir() function only creates a directory if its parent exists. In PHP 5 the recursive parameter was added which should be true or false, depending on whether you want to create parent directories or not. In the following example, we pass true as a third parameter to mkdir(), so this makes the function act recursively to create any missing parent directories.</p>
<div>&lt;?php<br />
<span style="color: #007700;">// will create /path/to/directory and<br />
// also create /path and /path/to if needed and allowed<br />
</span>mkdir(&#8220;/path/to/directory&#8221;, 0777, true);<br />
?&gt;</div>
<div id="seo_alrp_related"><h2>Posts Related to how to work with Directories in php</h2><ul><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/08/how-to-create-thumbnail-images-using-php/" rel="bookmark">How to Create Thumbnail Images using PHP</a></h3><p>Download Source This tutorial will describe how to create thumbnail images on the fly using PHP. Furthermore you will learn how to process a whole ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/05/php-ftp-functions-list/" rel="bookmark">PHP FTP Functions List</a></h3><p>ftp_cdup — Changes to the parent directory ftp_chdir — Changes directories on a FTP server ftp_close — Closes an FTP connection ftp_connect — Opens an ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2010/12/www-ab-directory-com-free-directory-submission-website/" rel="bookmark">www.ab-directory.com  free directory submission website</a></h3><p>New Web Directory: The New Web Site Directory A new internet directory of professionally reviewed web sites offering basic and express site submission.  www.ab-directory.com Local ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/05/php-file-handling-filesystem-functions-list/" rel="bookmark">PHP File Handling (Filesystem) Functions List</a></h3><p>basename — Returns filename component of path chgrp — Changes file group chmod — Changes file mode chown — Changes file owner clearstatcache — Clears ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2010/07/seo-faq-google-page-rank-pr/" rel="bookmark">SEO FAQ &#8211; Google Page Rank ( PR )</a></h3><p>1.) I am changing my domain but want to keep my PR, how do I do it? A 301 redirect is the most efficient and ...</p></div></li></ul></div>]]></content:encoded>
			<wfw:commentRss>http://www.bageshsingh.com/bagesh-blog/2011/08/how-to-work-with-directories-in-php/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to connect to MS SQL Server database</title>
		<link>http://www.bageshsingh.com/bagesh-blog/2011/08/how-to-connect-to-ms-sql-server-database/</link>
		<comments>http://www.bageshsingh.com/bagesh-blog/2011/08/how-to-connect-to-ms-sql-server-database/#comments</comments>
		<pubDate>Mon, 29 Aug 2011 17:26:42 +0000</pubDate>
		<dc:creator>Bagesh Singh</dc:creator>
				<category><![CDATA[Home]]></category>
		<category><![CDATA[how-to]]></category>
		<category><![CDATA[Interview Question]]></category>
		<category><![CDATA[mysql]]></category>
		<category><![CDATA[mysql interview question]]></category>
		<category><![CDATA[Others]]></category>
		<category><![CDATA[Php interview question]]></category>
		<category><![CDATA[tips and technique]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[ADODB]]></category>
		<category><![CDATA[DATABASE MSSQL]]></category>
		<category><![CDATA[DRIVER]]></category>
		<category><![CDATA[DSN]]></category>
		<category><![CDATA[PHP CONNECTION]]></category>
		<category><![CDATA[PRIN]]></category>
		<category><![CDATA[RETRIEVE]]></category>

		<guid isPermaLink="false">http://www.bageshsingh.com/bagesh-blog/?p=1443</guid>
		<description><![CDATA[Below is the code for connecting to a MSSQL Server database. &#60;?php $myServer = &#8220;localhost&#8221;; $myUser = &#8220;your_name&#8221;; $myPass = &#8220;your_password&#8221;; $myDB = &#8220;examples&#8221;; //connection to the database $dbhandle = mssql_connect($myServer, $myUser, $myPass) or die(&#8220;Couldn&#8217;t connect to SQL Server on $myServer&#8221;); //select a database to work with $selected = mssql_select_db($myDB, $dbhandle) or die(&#8220;Couldn&#8217;t open database [...]]]></description>
			<content:encoded><![CDATA[<p>Below is the code for connecting to a MSSQL Server database.</p>
<table cellspacing="1">
<tbody>
<tr>
<td id="post-main-8648" valign="top" width="100%">
<div>
<div>&lt;?php<br />
$myServer = &#8220;localhost&#8221;;<br />
$myUser = &#8220;your_name&#8221;;<br />
$myPass = &#8220;your_password&#8221;;<br />
$myDB = &#8220;examples&#8221;;</p>
<p>//connection to the database<br />
$dbhandle = mssql_connect($myServer, $myUser, $myPass)<br />
or die(&#8220;Couldn&#8217;t connect to SQL Server on $myServer&#8221;);</p>
<p>//select a database to work with<br />
$selected = mssql_select_db($myDB, $dbhandle)<br />
or die(&#8220;Couldn&#8217;t open database $myDB&#8221;);</p>
<p>//declare the SQL statement that will query the database<br />
$query = &#8220;SELECT id, name, year &#8220;;<br />
$query .= &#8220;FROM cars &#8220;;<br />
$query .= &#8220;WHERE name=&#8217;BMW&#8217;&#8221;;</p>
<p><span style="color: #007700;">//execute the SQL query and return records</span><br />
$result = mssql_query($query);</p>
<p>$numRows = mssql_num_rows($result);<br />
echo &#8220;&lt;h1&gt;&#8221; . $numRows . &#8221; Row&#8221; . ($numRows == 1 ? &#8220;&#8221; : &#8220;s&#8221;) . &#8221; Returned &lt;/h1&gt;&#8221;;</p>
<p><span style="color: #007700;">//display the results </span><br />
while($row = mssql_fetch_array($result))<br />
{<br />
echo &#8220;&lt;li&gt;&#8221; . $row["id"] . $row["name"] . $row["year"] . &#8220;&lt;/li&gt;&#8221;;<br />
}<br />
<span style="color: #007700;">//close the connection<br />
</span>mssql_close($dbhandle);<br />
?&gt;</div>
</div>
</td>
</tr>
</tbody>
</table>
<p>Connect with a DSN</p>
<p>DSN stands for &#8216;Data Source Name&#8217;. It is an easy way to assign useful and easily rememberable names to data sources which may not be limited to databases alone. If you do not know how to set up a system DSN read our tutorial How to set up a system DSN.</p>
<p>In the example below we will show you how to connect with a DSN to a MSSQL Server database called &#8216;examples.mdb&#8217;  and retrieve all the records from the table &#8216;cars&#8217;.</p>
<table cellspacing="1">
<tbody>
<tr>
<td id="post-main-8648" valign="top" width="100%">
<div>
<div>&lt;?php</p>
<p>//connect to a DSN &#8220;myDSN&#8221;<br />
$conn = odbc_connect(&#8216;myDSN&#8217;,&#8221;,&#8221;);</p>
<p>if ($conn)<br />
{<br />
//the SQL statement that will query the database<br />
$query = &#8220;select * from cars&#8221;;<br />
//perform the query<br />
$result=odbc_exec($conn, $query);</p>
<p>echo &#8220;&lt;table border=\&#8221;1\&#8221;&gt;&lt;tr&gt;&#8221;;</p>
<p>//print field name<br />
$colName = odbc_num_fields($result);<br />
for ($j=1; $j&lt;= $colName; $j++)<br />
{<br />
echo &#8220;&lt;th&gt;&#8221;;<br />
echo odbc_field_name ($result, $j );<br />
echo &#8220;&lt;/th&gt;&#8221;;<br />
}</p>
<p>//fetch tha data from the database<br />
while(odbc_fetch_row($result))<br />
{<br />
echo &#8220;&lt;tr&gt;&#8221;;<br />
for($i=1;$i&lt;=odbc_num_fields($result);$i++)<br />
{<br />
echo &#8220;&lt;td&gt;&#8221;;<br />
echo odbc_result($result,$i);<br />
echo &#8220;&lt;/td&gt;&#8221;;<br />
}<br />
echo &#8220;&lt;/tr&gt;&#8221;;<br />
}</p>
<p>echo &#8220;&lt;/td&gt; &lt;/tr&gt;&#8221;;<br />
echo &#8220;&lt;/table &gt;&#8221;;</p>
<p>//close the connection<br />
odbc_close ($conn);<br />
}<br />
else echo &#8220;odbc not connected&#8221;;<br />
?&gt;</p></div>
</div>
</td>
</tr>
</tbody>
</table>
<p>Connect without a DSN (using a connection string)</p>
<p>Let see a sample script to see how ADODB is used in PHP:</p>
<table cellspacing="1">
<tbody>
<tr>
<td id="post-main-8648" valign="top" width="100%">
<div>
<div>&lt;?php<br />
$myServer = &#8220;localhost&#8221;;<br />
$myUser = &#8220;your_name&#8221;;<br />
$myPass = &#8220;your_password&#8221;;<br />
$myDB = &#8220;examples&#8221;;</p>
<p>//create an instance of the  ADO connection object<br />
$conn = new COM (&#8220;ADODB.Connection&#8221;)<br />
or die(&#8220;Cannot start ADO&#8221;);</p>
<p>//define connection string, specify database driver<br />
$connStr = &#8220;PROVIDER=SQLOLEDB;SERVER=&#8221;.$myServer.&#8221;;UID=&#8221;.$myUser.&#8221;;PWD=&#8221;.$myPass.&#8221;;DATABASE=&#8221;.$myDB;<br />
$conn-&gt;open($connStr); <span style="color: #007700;">//Open the connection to the database</span></p>
<p><span style="color: #007700;">//declare the SQL statement that will query the database</span><br />
$query = &#8220;SELECT * FROM cars&#8221;;</p>
<p><span style="color: #007700;">//execute the SQL statement and return records</span><br />
$rs = $conn-&gt;execute($query);</p>
<p>$num_columns = $rs-&gt;Fields-&gt;Count();<br />
echo $num_columns . &#8220;&lt;br&gt;&#8221;;</p>
<p>for ($i=0; $i &lt; $num_columns; $i++) {<br />
$fld[$i] = $rs-&gt;Fields($i);<br />
}</p>
<p>echo &#8220;&lt;table&gt;&#8221;; while (!$rs-&gt;EOF)  <span style="color: #007700;">//carry on looping through while there are records</span><br />
{<br />
echo &#8220;&lt;tr&gt;&#8221;;<br />
for ($i=0; $i &lt; $num_columns; $i++) {<br />
echo &#8220;&lt;td&gt;&#8221; . $fld[$i]-&gt;value . &#8220;&lt;/td&gt;&#8221;;<br />
}<br />
echo &#8220;&lt;/tr&gt;&#8221;;<br />
$rs-&gt;MoveNext(); //move on to the next record<br />
}</p>
<p>echo &#8220;&lt;/table&gt;&#8221;;</p>
<p>//close the connection and recordset objects freeing up resources<br />
$rs-&gt;Close();<br />
$conn-&gt;Close();</p>
<p>$rs = null;<br />
$conn = null;<br />
?&gt;</p></div>
</div>
</td>
</tr>
</tbody>
</table>
<p>To create &#8216;examples&#8217; database on your MSSQL Server you should run the following script:</p>
<div>
<div>CREATE DATABASE examples;<br />
USE examples;<br />
CREATE TABLE cars(<br />
id int UNIQUE NOT NULL,<br />
name varchar(40),<br />
year varchar(50),<br />
PRIMARY KEY(id)<br />
);</p>
<p>INSERT INTO cars VALUES(1,&#8217;Mercedes&#8217;,&#8217;2000&#8242;);<br />
INSERT INTO cars VALUES(2,&#8217;BMW&#8217;,&#8217;2004&#8242;);<br />
INSERT INTO cars VALUES(3,&#8217;Audi&#8217;,&#8217;2001&#8242;);</p></div>
</div>
<div id="seo_alrp_related"><h2>Posts Related to How to connect to MS SQL Server database</h2><ul><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/08/how-to-make-dsn-and-dsn-less-connections/" rel="bookmark">How to make DSN and DSN-less connections</a></h3><p>DSN stands for 'Data Source Name'. It is an easy way to assign useful and easily rememberable names to data sources which may not be ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2010/11/paging-using-php-and-mysql/" rel="bookmark">Paging Using PHP and MySQL</a></h3><p>When there's more than one column involved in paging there isn't much that we need to modify. We only need to decide how to count ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/07/php-stored-procedures-and-sql-server/" rel="bookmark">PHP, Stored Procedures, and SQL Server</a></h3><p>While working on ezmp3, I had occasion to useMS SQL Server stored procedures from PHP. A couple of people I know always moan about blogs ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/08/php-export-database-schema-as-xml/" rel="bookmark">PHP: Export Database Schema as XML</a></h3><p>Sometimes it can be useful to have a dump of the current database schema. The script below reads the schema from a MySQL database and outputs ...</p></div></li><li><div class="seo_alrp_rl_content"><h3><a href="http://www.bageshsingh.com/bagesh-blog/2011/05/php-mysql-functions-list/" rel="bookmark">PHP Mysql Functions List</a></h3><p>mysql_affected_rows — Get number of affected rows in previous MySQL operation mysql_change_user — Change logged in user of the active connection mysql_client_encoding — Returns the ...</p></div></li></ul></div>]]></content:encoded>
			<wfw:commentRss>http://www.bageshsingh.com/bagesh-blog/2011/08/how-to-connect-to-ms-sql-server-database/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

