<?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>UseStrict Consulting &#187; PHP</title>
	<atom:link href="http://usestrict.net/category/php/feed/" rel="self" type="application/rss+xml" />
	<link>http://usestrict.net</link>
	<description>Professional IT Solutions &#38; Training</description>
	<lastBuildDate>Sat, 07 Jan 2012 14:05:03 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Introduction to Ajax</title>
		<link>http://usestrict.net/2009/08/introduction-to-ajax/</link>
		<comments>http://usestrict.net/2009/08/introduction-to-ajax/#comments</comments>
		<pubDate>Mon, 24 Aug 2009 21:56:08 +0000</pubDate>
		<dc:creator>vinny</dc:creator>
				<category><![CDATA[Ajax]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Perl]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[how to]]></category>

		<guid isPermaLink="false">http://usestrict.net/?p=840</guid>
		<description><![CDATA[Introduction to Ajax, Ajax how-to]]></description>
			<content:encoded><![CDATA[<p>In this article, I provide an explanation of Ajax with a historical introduction. If you are eager to start seeing the code, please scroll down.</p>
<p>&nbsp;</p>
<h3>What’s Ajax?</h3>
<p>&nbsp;</p>
<p>Ajax stands for <em>Asynchronous Javascript And XML</em>. It’s a way to call back-end scripts asynchronously – that is, without impacting user experience/flow. Basically, you don&#8217;t even see the cursor become an hourglass or whatever other &#8220;waiting/processing&#8221; icon your system uses. It&#8217;s not a language, but a technique. As for back-end scripts, you can use whatever you feel more comfortable with: PHP, Perl, Java, JSP, Shell, C, etc. The way to choose which technology to use as back-end is not outside the scope of this article.</p>
<p>&nbsp;</p>
<h3>Historical approach for calling back-end apps</h3>
<p>&nbsp;</p>
<p>Throughout web-development history, the very first way used to achieve back-end processing followed by front-end display was to create a form and set the back-end script as the action to that form. Upon submission, the form fields would be sent to the back-end script as a series of special environment variables, which would then be handled by the programmed logic. The back-end output would be displayed on the screen (either the same page/frame or a different page/frame, depending on the target attribute of the form).</p>
<p>The catch 22 of this approach is that if you want to present another form after processing, that form must be produced by the back-end script, which leads to maintenance mayhem – to add or remove a field, you have to do so in both the original HTML and in the HTML of the back-end script.</p>
<p><span id="more-840"></span></p>
<p>&nbsp;</p>
<h3>Hidden IFRAMES and Javascript to the rescue</h3>
<p>&nbsp;</p>
<p>The natural evolution of the regular form submission was to avoid having to generate HTML from the back-end script. A technique that I eventually came up with (had never seen it before, but it was probably already out there) prior to adhering to Ajax was using a hidden IFRAME as target to a simple form containing an <em>action_cd</em> field and a <em>data</em> field. There would not be a regular submit button, but a set of input elements with <em>onclick</em> or <em>onchange</em> events and a regular (non-submit) button at the end. </p>
<p>In this approach, Javascript did all the work – when the user clicked the pseudo-submit button, an <em>onclick</em> event would read all the input fields and join them like a regular HTTP query (<code>field1=val1&#038;field2=val2</code>…). The <em>action_cd</em> value would be dynamically evaluated and the back-end script would receive the data string and action code and process it. Javascript would perform the submission when, say, a value of a drop-down field was selected, and the output would be a series of dynamically generated Javascript commands inside the IFRAME. Those commands would manipulate the user’s form (e.g. Auto-populate a &#8220;state&#8221; drop-down after selecting a &#8220;country&#8221; value). </p>
<p>Although this approach successfully handled the no-longer-need to submit and reload a form, it still had 2 main downsides: generating and maintaining Javascript code is not a simple task (especially due to having to escape quotes), and the whole procedure was still synchronous – you could see the hourglass, browser process bars, clicking sounds (IE), etc. It&#8217;s much better user experience, but still not the real deal, seamless/transparent back-end processing.</p>
<p>&nbsp;</p>
<h3>The XmlHttpRequest object</h3>
<p>&nbsp;</p>
<p>Javascript back-end calls are made possible thanks to the <em>XmlHttpRequest</em> object that most modern browsers now support. For IE 6 and older, it is done through an ActiveXObject. </p>
<p>&nbsp;</p>
<h3>Javascript code to initialize Ajax object</h3>
<p>&nbsp;</p>
<pre class="brush:javascript">

var xmlHttp; // global variable. It’s important for later on

function GetXmlHttpObject(){

      if (window.XMLHttpRequest){
        // code for IE7+, Firefox, Chrome, Opera, Safari
        return new XMLHttpRequest();
      }

      if (window.ActiveXObject){
        // code for IE6, IE5
        return new ActiveXObject("Microsoft.XMLHTTP");
      }
      return null;
}
</pre>
<p>It&#8217;s important to have a global variable in which to assign the XMLHttpRequest object, since this technique has its shortcomings when dealing with passing variables around. We&#8217;ll understand that better shortly. The function checks for the existence of <strong>window.XMLHttpRequest</strong> which is used in IE7 (finally, it complies to standards!), Firefox, and other non IE browsers, and checks for <strong>window.ActiveXObject</strong> existence for IE6 and 5. I’m not sure if this works on IE4 – it probably does not, but hopefully IE4 is already in extinction. If neither checks work, it returns null, which will be handled in the function calling the XMLHttpObject.</p>
<p>&nbsp;</p>
<h3>Making Synchronous Ajax calls (GET method)</h3>
<p>&nbsp;</p>
<p>Although the hype of Ajax is due to the &#8220;Asynchronosity&#8221; of the technique, it is also capable of making synchronous calls. Synchronous calls are important in cases where you don&#8217;t want to allow the user to do something while the back-end is checking a previous action, but also don&#8217;t want to have to submit the whole form.</p>
<pre class="brush:javascript">

function synch_call() {

      // initialize Ajax object
      var xmlHttp = GetXmlHttpObject(); 

      // Set the URL to your backend script with query vars
      var url = “/url/to/your/backend/script?with=var1&#038;and=var2”;

      // Synchronous call
      xmlHttp.open("GET",url,false); // "false" means asynchronous = false
      xmlHttp.send(null);

      // the code above does the back-end call. Now we handle the response
      // this function continues further down in the tutorial

}
</pre>
<p>Ajax calls can be done using GET or POST methods. I recommend GET methods for small queries, POST for large ones. There used to be a limit of 255 characters on URL fields – not sure if a) this is still true; b) this could apply to these Ajax techniques.</p>
<p>The call to the back-end is done by 2 commands: <strong>xmlHttp.open(Method,url,async)</strong>, and the <strong>xmlHttp.send(null)</strong> calls. For POST method, this is a little different, so we’ll stick to GET calls for the time being.</p>
<p>&nbsp;</p>
<h3>Handling back-end reply</h3>
<p>&nbsp;</p>
<p><em>Asynchronous Javascript And XML</em> isn&#8217;t the perfect name for Ajax. It should be more like Aja<strong>R</strong>, where R stands for Reply. The reason is because the reply can be either an XML structure or a plain text. We use <strong>xmlHttp.responseXML.documentElement</strong> if we’re handling XML, or a plain <strong>xmlHttp.responseText</strong> for plain text. Actually, we can use the latter for XML as well, especially when debugging the code (when you want to pop up the XML reply).</p>
<p>We use a try/catch block to capture any errors:</p>
<pre class="brush:javascript">
function synch_call() {

      // initialize Ajax object
      var xmlHttp = GetXmlHttpObject(); 

      // Set the URL to your backend script with query vars
      var url = “/url/to/your/backend/script?with=var1&#038;and=var2”;

      // Synchronous call

      xmlHttp.open("GET",url,false); // “false” means asynchronous = false
      xmlHttp.send(null);

      // the code above does the back-end call. Now we handle the response
      try {            

            alert("Ajax Response: n"+xmlHttp.responseText); // Just pop-up the reply
            return false;
      }
      catch(e) {
            alert(e); // if error, show it as a pop-up
            return false;
      }
}
</pre>
<p>&nbsp;</p>
<p>To handle the  reply as XML, you need to a) make sure your back-end script outputs an XML structure, and b), replace xmlHttp.reponseText for xmlHttp.responseXML.documentElement.</p>
<p>&nbsp;</p>
<pre class="brush:javascript">
// Just the try/catch block changed        

       try {
              data = xmlHttp.responseXML.documentElement;
        }
        catch(e) {
               alert(e);
               return false;
        }
</pre>
<p>The <code>data</code> variable now holds a DOM object of the XML structure. To access its elements, we use DOM functions. </p>
<p>Example XML structure:</p>
<pre class="brush:xml">
&lt;OUT&gt;
      &lt;STATUS&gt;Success&lt;/STATUS&gt;
      &lt;MSG type="some_type"&gt;This is a test message&lt;/MSG&gt;
&lt;/OUT&gt;
</pre>
<p>Accessing Example XML through DOM:</p>
<pre class="brush:javascript">

      // gets the Success text
      var msg_status = data.getElementsByTagName(‘STATUS’)[0].childNodes[0].nodeValue;

      // Assign MSG object to msg variable
      var msg = data.getElementsByTagName(‘MSG’)[0]; 

      // gets the attribute “type”
      var msg_type = msg.getAttribute(‘type’); 

      // gets the text inside the MSG node
      var msg_text = msg.childNodes[0].nodeValue;
</pre>
<p>&nbsp;</p>
<h3>Putting it all together</h3>
<p>&nbsp;</p>
<pre class="brush:javascript">
function synch_call() {

      // initialize Ajax object
      var xmlHttp = GetXmlHttpObject(); 

      // Set the URL to your backend script with query vars
      var url = “/url/to/your/backend/script?with=var1&#038;and=var2”; 

      // Synchronous call
      xmlHttp.open("GET",url,false); // "false" means asynchronous = false
      xmlHttp.send(null);

      // the code above does the back-end call. Now we handle the response

      try {
            data = xmlHttp.responseXML.documentElement;
       }
       catch(e) {
             alert(e);
             return false;
       }

      // gets the Success text
      var msg_status = data.getElementsByTagName(‘STATUS’)[0].childNodes[0].nodeValue; 

      // Assign MSG object to msg variable
      var msg = data.getElementsByTagName(‘MSG’)[0]; 

      // gets the attribute “type”
      var msg_type = msg.getAttribute(‘type’); 

      // gets the text inside the MSG node
      var msg_text = msg.childNodes[0].nodeValue;
      alert("Got the following backend reply: " + msg_status + "n" + msg + "n" + msg_type + "n" + msg_text);

      return true;
}
</pre>
<p>&nbsp;</p>
<h3>Making Asynchronous Ajax calls (GET method)</h3>
<p>&nbsp;</p>
<p>We saw on page 2 that what controls synchronicity of the Ajax call is the true/false value in the <code>open()</code> command. However, we also need changes in the way we handle the reply. We do that by setting <strong><em>onreadystatechange</em></strong> property on the xmlHttp object.</p>
<p> OnReadyStateChange should be a function that will check the <em><strong>readyState</strong></em> attribute of the xmlHttp object.</p>
<p>&nbsp;</p>
<h3>Understanding readyState</h3>
<p>&nbsp;</p>
<p>readyStates are the way Javascript controls what stage of the process the call is in. It ranges from 0 to 4, where 4 is the completed reply from the back-end script. We normally only care about readyState == 4. Here are the codes and meaning:</p>
<table>
<tr>
<td><strong>Value</strong></td>
<td><strong>State</strong></td>
</tr>
<tr>
<td>0</td>
<td>Uninitialized</td>
</tr>
<tr>
<td>1</td>
<td>Loading</td>
</tr>
<tr>
<td>2</td>
<td>Loaded</td>
</tr>
<tr>
<td>3</td>
<td>Interactive</td>
</tr>
<tr>
<td>4</td>
<td>Complete</td>
</tr>
</table>
<p>&nbsp;</p>
<h3>Setting onreadystatechange</h3>
<p>&nbsp;</p>
<p><code>onreadystatechange</code> can be assigned a anonymous <code>function() {  }</code> block, or a named function. Just be careful with function parameters – to this day, I have not been able to pass any parameters to the functions set to <code>onreadystatechange</code>. Hence the need for some global variables in play.</p>
<p>Let&#8217;s copy over our <code>sync_call()</code> function and make it <code>Async_call()</code></p>
<pre class="brush:javascript">
function Asynch_call() {

      // initialize Ajax object
      var xmlHttp = GetXmlHttpObject(); 

      // Set the URL to your backend script with query vars
      var url = “/url/to/your/backend/script?with=var1&#038;and=var2”;

      // onreadystatechange must be set BEFORE making the call

      // it takes the response handling code that we had in the sync_call() previously
      xmlHttp.onreadystatechange = function() {

            if (xmlHttp.readyState == 4) { // Complete

                  // Now we handle the response within the onreadystatechange
                  try {
                        data = xmlHttp.responseXML.documentElement;
                  }
                  catch(e) {
                        alert(e);
                        return false;
                  }

                  // gets the Success text
                  var msg_status = data.getElementsByTagName(‘STATUS’)[0].childNodes[0].nodeValue; 

                  // Assign MSG object to msg variable
                  var msg = data.getElementsByTagName(‘MSG’)[0]; 

                  // gets the attribute "type"
                  var msg_type = msg.getAttribute('type'); 

                  // gets the text inside the MSG node
                  var msg_text = msg.childNodes[0].nodeValue;

                  alert("Got the following backend reply: " + msg_status + "n" + msg + "n" + msg_type + "n" + msg_text);
                  return true;
            }

      }; // don’t forget the ';' at the end of the function() {} block!!

      // Asynchronous call
      xmlHttp.open("GET",url,true); // 'true' means asynchronous = true
      xmlHttp.send(null);
}
</pre>
<p>&nbsp;</p>
<p>As mentioned before, you can separate the anonymous function assignment into a named function. The good side of this is that your functions get more manageable, but the downside is that you might need global variables in order to share values between the main function and the <code>onreadystatechange,/code> function.</p>
<p>&nbsp;</p>
<pre class="brush:javascript">
function Asynch_call() {

      // initialize Ajax object
      var xmlHttp = GetXmlHttpObject(); 

      // Set the URL to your backend script with query vars
      var url = “/url/to/your/backend/script?with=var1&#038;and=var2”; 

      // onreadystatechange must be set BEFORE making the call

      // it takes the response handling code that we had in the sync_call previously
      xmlHttp.onreadystatechange = handlerfunction; // See separate function below    

      // Asynchronous call
      xmlHttp.open("GET",url,true); // “true” means asynchronous = true
      xmlHttp.send(null);
}

function handlerfunction() {

      if (xmlHttp.readyState == 4) { // Complete – must be global xmlHttp variable

            // Now we handle the response within the onreadystatechange
            try {
                  data = xmlHttp.responseXML.documentElement;
            }
            catch(e) {
                  alert(e);
                  return false;
            }

             // gets the Success text
            var msg_status = data.getElementsByTagName(‘STATUS’)[0].childNodes[0].nodeValue; 

            // Assign MSG object to msg variable
            var msg = data.getElementsByTagName(‘MSG’)[0]; 

            // gets the attribute “type”
            var msg_type = msg.getAttribute(‘type’); 

            // gets the text inside the MSG node
            var msg_text = msg.childNodes[0].nodeValue;

            alert("Got the following back-end reply: " + msg_status + "n" + msg + "n" + msg_type + "n" + msg_text);
            return true;

      }
}
</pre>
<p>&nbsp;</p>
<h3>Parsing forms to create the GET/POST strings</h3>
<p>&nbsp;</p>
<p>Since we are not submitting the form with the usual submit button, we have to handle building the queries ourselves. I came up with a function that mimics the way browsers handle function calls.</p>
<pre class="brush:javascript">
function build_post_string(frm) {

      var str;
      var poststr_array = [];

      if (!frm.id) {
            // assume it's a string. get the form object
            frm = document.getElementById(frm);
      }

      for (i=0;i&lt;frm.elements.length;i++){

            var elem = frm.elements[i];

            if (!elem.id) {
                  // skip any fields that don't have IDs
                  continue;
            }

            if (elem.type == 'radio' || elem.type == 'checkbox') {

                  // only grab radio buttons and checkboxes that are checked
                  if (!elem.checked) {
                        continue;
                  }

            }            

            // get select values
            if (elem.nodeName.match(/SELECT/i) &#038;&#038; elem.multiple) {

                  var sel_array = [];

                  for (var o=0;o&lt;elem.options.length;o++) {

                        if (elem.options[o].selected) {
                              sel_array[sel_array.length] = elem.id+"="+elem.options[o].value;
                        }

                  }

                  var sel_str = sel_array.join('&#038;');

                  // build key/value pairs for SELECTs
                  poststr_array[poststr_array.length] = sel_str;
            }
            else if (elem.nodeName.match(/SELECT/i)) {
                  poststr_array[poststr_array.length] = elem.id+'='+elem.options[elem.selectedIndex].value;
            }
            else {
                  // build key/value pairs for everything else
                  poststr_array[poststr_array.length] = elem.id+"="+elem.value;
            }

      }

      // build and return str
      str = poststr_array.join("&#038;");
      return str;
}
</pre>
<p>This function takes a given form by ID and iterates through all of its elements. It is important that all fields you want in the query have an ID attribute. Otherwise they will be skipped. <strong>The return from this function can be used for both GET and POST requests.</strong></p>
<p>&nbsp;</p>
<h3>Using POST method for Ajax calls</h3>
<p>&nbsp;</p>
<p>So far we saw that making GET calls is pretty straight-forward. POST calls are different in the way that they are not put in the HTTP Header, but rather in a separate packet. In order to do that, we need to set a few header variables:</p>
<pre class="brush:javascript">
function Asynch_call_with_post() {

      // initialize Ajax object
      var xmlHttp = GetXmlHttpObject(); 

      // Set the URL to your backend script with query vars
      var post_str = build_post_string(‘my_form’); 

      var url = “/url/to/your/backend/script?” + post_str;

      // onreadystatechange must be set BEFORE making the call
      // it takes the response handling code that we had in the sync_call previously
      xmlHttp.onreadystatechange = function() {

            if (xmlHttp.readyState == 4) { // Complete

                   // Now we handle the response within the onreadystatechange
                   try {
                         data = xmlHttp.responseXML.documentElement;
                    }
                    catch(e) {
                         alert(e);
                         return false;
                    }

                     // gets the Success text
                     var msg_status = data.getElementsByTagName(‘STATUS’)[0].childNodes[0].nodeValue; 

                      // Assign MSG object to msg variable
                     var msg = data.getElementsByTagName(‘MSG’)[0]; 

                     // gets the attribute “type”
                     var msg_type = msg.getAttribute(‘type’); 

                     // gets the text inside the MSG node
                     var msg_text = msg.childNodes[0].nodeValue;
                     alert("Got the following backend reply: " + msg_status + "n" + msg + "n" + msg_type + "n" + msg_text);
                     return true;
               }

        }; // don't forget the ';' at the end of the function() {} block

        // Asynchronous call
        xmlHttp.open('POST',url, true); // Replace "GET" with "POST"

        // Set headers
        xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xmlHttp.setRequestHeader("Content-length", url.length);
        xmlHttp.setRequestHeader("Connection", "close");

        // Send the packet. Note that it’s no longer null as parameter to send
        xmlHttp.send(url);
}
</pre>
<p>&nbsp;</p>
<h3>Showing/Hiding "Processing…" messages</h3>
<p>&nbsp;</p>
<p>Since Ajax in Asynchronous mode is 100% transparent to the user, it is necessary to handle our own messages asking the user to wait until processing finishes. The simplest way to do this is by using a <code>DIV</code> element with initial display property set as none, or visibility set as hidden (the difference is that <code>visibility="hidden"</code> makes the element still occupy its space in the page, whereas <code>display="none"</code> effectively removes the element from the page and the space that it occupied).</p>
<p>Typically, I include code to show the element in the Ajax function, and code to hide it again in the <em>onreadystatechange</em> function (where readyState == 4). </p>
<pre class="brush:javascript">
        document.getElementById(‘wait_image’).display = ‘block’;
        document.getElementById(‘wait_image’).display = ‘none’;
</pre>
<p>&nbsp;</p>
<h3>Third-Party AJAX Libraries</h3>
<p>&nbsp;</p>
<p>There are several Ajax in a box libraries out there, but I am not comfortable with using them for company applications. The reason being is that Ajax is very powerful and can very well make calls to the maintainer's website to steal/capture sensitive information.  </p>
<p>Google provides Java code that generates Ajax during build – that is a typical example of us not being able to control Ajax code generated. </p>
<p>&nbsp;</p>
<h3>Testing the back-end script</h3>
<p>&nbsp;</p>
<p>There are 2 simple ways of testing the back-end script. With PHP, you can access both GET and POST variables through the <code>$_REQUEST</code> array. Perl CGI doesn’t really care if it’s GET or POST. I don’t know how JSP can handle it. With this being said, I simply have the Ajax alert the URL variable and return false. I then copy the URL variable and paste it in another window to see the output.</p>
<p>I strongly recommend debugging with Firefox – it has a handy error console and also parses the output XML or complains if it’s not built right.</p>
<p>&nbsp;</p>
<h3>Keeping IE from crashing with the XMLs</h3>
<p>&nbsp;</p>
<p>I'm pretty sure that Microsoft IE developers have some satisfaction in making web developers go crazy. That's how I felt when I started working with XML and Ajax, and although my app was working fine in Firefox, it kept crashing bad in IE. After some googling, I found out that I needed to set some headers in order to keep IE from blowing up. I already had the <code>"Content-type: text/xml"</code> header in place, but it appears that IE needs some caching control and expiry headers as well.</p>
<p>This is what I use in PHP:</p>
<pre class="brush:php">
        header("Expires: Fri, 09 Jan 1981 05:00:00 GMT");
        header("Cache-Control: no-store, no-cache, must-revalidate");
        header("Cache-Control: post-check=0, pre-check=0", FALSE); // FALSE means add this Cache-Control line instead of replacing the previous one
        header("Pragma: no-cache");
        header("Content-type: text/xml");
</pre>
<p>In Perl, setting headers is simple: just <code>print</code> them before printing any content. When you're done printing all your headers, print an empty newline to indicate where the page content will go.</p>
<p>I hope you've enjoyed this tutorial. Feel free to paste comments regarding your experience and preferences.</p>
<p>&nbsp;</p>
<h3>Book Suggestions:</h3>
<p>&nbsp;</p>
<div>
<script type="text/javascript">
    (function(){
        document.write('<script type="text/javascript" src="http://cb1.cronblocks.com//js/content.js?c=14&#038;t='+(Math.floor(new Date().getTime()/1000))+'&#038;s=client"><\/script>');
    })();
</script><br />
</script>
</div>
]]></content:encoded>
			<wfw:commentRss>http://usestrict.net/2009/08/introduction-to-ajax/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>PHP+PDO+MySQL: How I&#8217;m doing it and a question&#8230;</title>
		<link>http://usestrict.net/2009/08/phppdomysql-how-im-doing-it-and-a-question/</link>
		<comments>http://usestrict.net/2009/08/phppdomysql-how-im-doing-it-and-a-question/#comments</comments>
		<pubDate>Thu, 13 Aug 2009 12:47:18 +0000</pubDate>
		<dc:creator>vinny</dc:creator>
				<category><![CDATA[MySQL]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[PDO]]></category>
		<category><![CDATA[Select]]></category>
		<category><![CDATA[SQL]]></category>
		<category><![CDATA[Update]]></category>

		<guid isPermaLink="false">http://usestrict.net/?p=832</guid>
		<description><![CDATA[Example of PHP+PDO+MySQL usage to select and update arbitrary fields. Only one prepared statement is used for updating the data.]]></description>
			<content:encoded><![CDATA[<p>I recently decided to rewrite an application that I created for an English school where I used to work, and this time I want to do it right. I chose to write it in PHP with Object Orientation in mind, and use PDO+MySQL for the DAO portion.</p>
<p>The reason for using PDO is that it&#8217;s the closest thing to the DBI that I found for PHP &#8211; and the reason for PHP is that it&#8217;s just plain simpler than using pure Perl, and I don&#8217;t have the time to learn Catalyst or some other Perl Web framework.</p>
<p>Anyway, here&#8217;s what I&#8217;m doing for the PDO portion.</p>
<p>First I created a <code>Db</code> class which is just a DB connection wrapper.</p>
<pre class="brush:php">
&lt;?php
class Db{

	public $dbh  = null;

	public function Db($db_type,$db_host,$db_user,
			         $db_pass,$db_base,$tbl_prefix){

		if ($db_type == 'mysql') { // in case I want to add oracle in the future

			$mysql_DSN = "mysql:host=".$db_host.";dbname=".$this->db_base;

			try {
				$this->dbh = new PDO($mysql_DSN, $db_user, $db_pass,
							   array(PDO::ATTR_PERSISTENT => true, PDO::ERRMODE_WARNING => true,
							         PDO::ATTR_ERRMODE => true));

			}
			catch(PDOException $e){
				$rc[msg] = $e->getMessage();
				die($rc[msg] . "  " . __LINE__);
			}

			return $this->dbh;

		}

	}

}
?&gt;
</pre>
<p>Secondly, I created the DAO classes which extend the DB. They are responsible for <code>prepare</code>&#8216;ing and <code>execute</code>&#8216;ing the queries, and returning the data. Here&#8217;s an example one (I stripped some bells and whistles in order to not confuse anyone):</p>
<pre class="brush:php">
&lt;?php
class StudentsDao extends Db {

	public $sth = array();

	// Constructor
	public function StudentsDao($db_type=NULL,$db_host=NULL,$db_user=NULL,
				  	       $db_pass=NULL,$db_base=NULL,$tbl_prefix=NULL) { // These params are to be passed to Db class

		// Connect to DB
		$this->Db($db_type,$db_host,$db_user,
			      $db_pass,$db_base,$tbl_prefix);

		// Prepares queries
		$this->sth = $this->prepare($tbl_prefix); // Look at prepare() further down

	} // end of function StudentsDao

	// Function that prepares queries
	public function prepare() {

		$sth = null; // will hold our temporary array

		// get all students
		$string = sprintf('select * from %s.%sstudents where id = ?',DB_BASE,TBL_PREFIX);	// I have these constants defined in the main page
		$sth['getStudentById'] = $this->dbh->prepare($string);

		// update Student by Id
		$string = sprintf('update %s.%sstudents
				   set field1 = ?, field2 = ?, field3 = ?
				   where id = ?',DB_BASE,TBL_PREFIX);	// Note that this table has 3 control fields (id, sys_creation_date, and sys_update_date)  prior to field1, field2, and field3 - I don't want them to be touched

		$sth['updStudentById'] = $this->dbh->prepare($string);

		return $sth;

	} // end of prepare()

	// Here we have the handlers for the queries prepared above.

	// Fetches all students
	public function getStudentById($id) {

		$s = $this->sth['getStudents'];
		$s->execute(array($id)) || die(print_r($s->errorInfo,1));
		$result = $s->fetchAll(PDO::FETCH_ASSOC);

		if (sizeof($result) == 0) {
			// no data found
			$out[err_cd] = 1;
		}
		else {
			// data was found
			$out[err_cd] = 0;
			$out[data] = $result;
		}

		return $out;

	}

	// Updates student by Id - this is a tricky one
	public function updateStudentById($data,$id){ // $data can have data regarding one or more fields

		// Populate current fields
		$fields = $this->getStudentById($id); // get current values

		// Remove unwanted fields
		$fields = array_slice($fields[data][0],3); // remove the 3 initial control fields

		// Replace with new fields
		foreach($data as $k=>$v){
			$fields[strtolower($k)] = $v;
		}
		$fields['id'] = $id;

		$s = $this->sth['updStudentById'];
		$s->execute(array_values($fields)) || die(print_r($s->errorInfo,1));
		$count = $s->rowCount();

		if ($count == 1) {
			$out[err_cd] = 0;
		}
		else {
			$out[err_cd] = -1;
		}
		$out[err_msg] = $this->status[$out[err_cd]];
		return $out;

	}
?&gt;
</pre>
<p>In the example above, you will probably frown on the fact that I&#8217;m calling <code>getStudentById()</code> at the beginning of <code>updateStudentById()</code>. It&#8217;s OK &#8211; I frown on it, too. Let me explain why I did that:</p>
<p>I wanted to be able to pass the function an associative array containing only the fields I want to update &#8211; be it only <code>field1</code>, or <code>field1</code> and <code>field2</code> and so on. But I wanted to do that against my already prepared query, and not touching any additional fields. In my application, <code>students</code> table has a BUNCH of fields. In other words, update any given field or set of fields using the single prepared statement, <strong>without</strong> having to set ALL the fields in <code>$data</code></p>
<p>My original idea was to basically, to emulate something like this:</p>
<p><code> update students set field1=field1, field2='some new value ', field3=field3 where id = 1</code></p>
<p>That would set <code>field1</code> to whatever value <code>field1</code> already had. </p>
<p><strong>Here&#8217;s the question part:<br />
Unfortunately, I couldn&#8217;t figure out how to do that using the PDO (how to bind a field name instead of a value against the <code>?</code>-mark). If you know how to do that, do leave a comment explaining how! <img src='http://usestrict.net/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /><br />
</strong></p>
<p>The technique shown in the example will basically pull all values from the record and populate them in the <code>$fields</code> array. The <code>array_slice()</code> is used to remove the control fields that I have in my table, and the rest gets compared against the <code>$data</code> array and if any matching fields are found in <code>$data</code>, those fields get their values assigned over the existing <code>$fields</code> values.</p>
]]></content:encoded>
			<wfw:commentRss>http://usestrict.net/2009/08/phppdomysql-how-im-doing-it-and-a-question/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>PHP/Apache quick troubleshooting</title>
		<link>http://usestrict.net/2009/01/phpapache-quick-troubleshooting/</link>
		<comments>http://usestrict.net/2009/01/phpapache-quick-troubleshooting/#comments</comments>
		<pubDate>Sun, 11 Jan 2009 03:06:01 +0000</pubDate>
		<dc:creator>vinny</dc:creator>
				<category><![CDATA[Apache]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[troubleshooting]]></category>

		<guid isPermaLink="false">http://usestrict.net/?p=148</guid>
		<description><![CDATA[Troubleshooting Apache/PHP install]]></description>
			<content:encoded><![CDATA[<p>Just finished installing Apache+PHP on my machine after having it remastered&#8230; After recovering the &lt;VirtualHost&gt; settings from my old httpd.conf, and setting up PHP using the msi, all my old PHP pages were either simply not parsing the PHP code, or sometimes even printing it on the screen &#8211; NOT what I wanted.</p>
<p>So here&#8217;s a little heads up for anyone having the same problem:</p>
<p>a) Check your apache error logs. You&#8217;ll probably find them under your &lt;ApacheInstallDir&gt;/logs/<strong>error_log</strong></p>
<p>b) Verify that you have the <strong>AddType</strong> directive for PHP in your <strong>httpd.conf</strong> (<em><strong>AddType application/x-httpd-php .php</strong></em>); as well as the other settings for PHP (check install.txt file in your PHP directory)</p>
<p>c) Look for the <em><strong>short_open_tag</strong></em> directive in your <strong>php.ini</strong> file and set it to On if you want to be able to use <strong>&lt;?</strong> instead of only <strong>&lt;?php</strong></p>
<p>d) Make sure the <strong><em>display_startup_errors</em></strong> directive is set to <strong>On</strong></p>
<p>The culprit in my case was item c). I don&#8217;t have the patience of typing the 3 extra characters to open my PHP code, and PHP was simply ignoring it all.</p>
<p>Hope this helps.</p>
<p>[ad#middle_end] </p>
]]></content:encoded>
			<wfw:commentRss>http://usestrict.net/2009/01/phpapache-quick-troubleshooting/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>DBD::Oracle + Cygwin: Undefined reference error during make</title>
		<link>http://usestrict.net/2009/01/dbdoracle-cygwin-error-during-make/</link>
		<comments>http://usestrict.net/2009/01/dbdoracle-cygwin-error-during-make/#comments</comments>
		<pubDate>Wed, 07 Jan 2009 20:57:14 +0000</pubDate>
		<dc:creator>vinny</dc:creator>
				<category><![CDATA[Cygwin]]></category>
		<category><![CDATA[Oracle]]></category>
		<category><![CDATA[Perl]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[dbd::oracle]]></category>
		<category><![CDATA[dbi]]></category>
		<category><![CDATA[_OCILobGetChunkSize]]></category>
		<category><![CDATA[_OCINlsCharSetIdToName]]></category>

		<guid isPermaLink="false">http://usestrict.net/?p=138</guid>
		<description><![CDATA[Yesterday I found myself in a position of having to re-master my computer &#8211; hence having to reinstall most of the applications including my trusty Cygwin &#8211; which always becomes somewhat of a headache when I reach the point of installing DBD::Oracle in it. This time I got a undefined symbol error. A quick look [...]]]></description>
			<content:encoded><![CDATA[<p>Yesterday I found myself in a position of having to re-master my computer &#8211; hence having to reinstall most of the applications including my trusty Cygwin &#8211; which always becomes somewhat of a headache when I reach the point of installing DBD::Oracle in it.</p>
<p>This time I got a undefined symbol error. A quick look in <a href="http://www.nntp.perl.org/group/perl.dbi.users/2008/09/msg33238.html" target="_blank">Google</a> showed me that Erik Squires had the same exact problem. Lots of searching later, I find that Google can&#8217;t find a handy solution anywhere&#8230; So I send Erik an email asking about the solution and to my surprise, he answers only 1 (!!)  minute after I click send. Talk about a fast reply!!</p>
<p>Hats off to Erik! You will find the solution here: http://cpae.typepad.com/capacity_planning_and_eng/</p>
<p><strong>Hint:</strong> the <em>oci.def</em> that he mentions in his post is inside your DBD::Oracle build directory. Don&#8217;t get it confused with ocidef.h file in your $ORACLE_HOME/oci/include directory (that&#8217;s where I looked first).</p>
<p>I&#8217;m adding the error message below with a big SOLUTION header for any Googler out there having the same problem. No need to keep reading if the text above was enough to solve your problem.</p>
<p><span id="more-138"></span></p>
<p>Oracle 10g + DBD::Oracle + Cygwin issue</p>
<p>Make error:</p>
<p>&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8211;</p>
<pre>cp Oracle.pm blib/lib/DBD/Oracle.pm
cp oraperl.ph blib/lib/oraperl.ph
cp dbdimp.h blib/arch/auto/DBD/Oracle/dbdimp.h
cp ocitrace.h blib/arch/auto/DBD/Oracle/ocitrace.h
cp Oraperl.pm blib/lib/Oraperl.pm
cp Oracle.h blib/arch/auto/DBD/Oracle/Oracle.h
cp lib/DBD/Oracle/GetInfo.pm blib/lib/DBD/Oracle/GetInfo.pm
cp mk.pm blib/arch/auto/DBD/Oracle/mk.pm
/usr/bin/perl.exe -p -e "s/~DRIVER~/Oracle/g" /usr/lib/perl5/site_perl/
5.10/i686
-cygwin/auto/DBI/Driver.xst &gt; Oracle.xsi
/usr/bin/perl.exe /usr/lib/perl5/5.10/ExtUtils/xsubpp  -typemap /usr/
lib/perl5/5
.10/ExtUtils/typemap -typemap typemap  Oracle.xs &gt; Oracle.xsc &amp;&amp; mv
Oracle.xsc O
racle.c
gcc -c  -IC:/oracle/product/10.2.0/client_1/oci/include -IC:/oracle/
product/10.2
.0/client_1/rdbms/demo -I/usr/lib/perl5/site_perl/5.10/i686-cygwin/
auto/DBI -DPE
RL_USE_SAFE_PUTENV -U__STRICT_ANSI__ -fno-strict-aliasing -pipe -I/usr/
local/inc
lude -DUSEIMPORTLIB -O3   -DVERSION="1.22" -DXS_VERSION="1.22"  "-
I/usr/lib/
perl5/5.10/i686-cygwin/CORE"  -Wall -Wno-comment -DUTF8_SUPPORT -
DNEW_OCI_INIT -
DORA_OCI_VERSION="10.2.0.1" Oracle.c
gcc -c  -IC:/oracle/product/10.2.0/client_1/oci/include -IC:/oracle/
product/10.2
.0/client_1/rdbms/demo -I/usr/lib/perl5/site_perl/5.10/i686-cygwin/
auto/DBI -DPE
RL_USE_SAFE_PUTENV -U__STRICT_ANSI__ -fno-strict-aliasing -pipe -I/usr/
local/inc
lude -DUSEIMPORTLIB -O3   -DVERSION="1.22" -DXS_VERSION="1.22"  "-
I/usr/lib/
perl5/5.10/i686-cygwin/CORE"  -Wall -Wno-comment -DUTF8_SUPPORT -
DNEW_OCI_INIT -
DORA_OCI_VERSION="10.2.0.1" dbdimp.c
dbdimp.c: In function `ora_db_login6':
dbdimp.c:450: warning: cast to pointer from integer of different size

{ A bunch more cast and int format warnings from oci8.c}

rm -f blib/arch/auto/DBD/Oracle/Oracle.dll
LD_RUN_PATH="C:/oracle/product/10.2.0/client_1/lib:C:/oracle/product/
10.2.0/clie
nt_1/rdbms/lib" g++  --shared  -Wl,--enable-auto-import -Wl,--export-
all-symbols
 -Wl,--stack,8388608 -Wl,--enable-auto-image-base -L/usr/local/lib
Oracle.o dbdi
mp.o oci8.o  -o blib/arch/auto/DBD/Oracle/Oracle.dll
          /usr/lib/perl5/5.10/i686-cygwin/CORE/libperl.dll.a -L/
cygdrive/c/cpan/
5.10.0/build/DBD-Oracle-1.22 -loci      

Oracle.o:Oracle.c:(.text+0x6ba9): undefined reference to
`_OCILobGetChunkSize'
dbdimp.o:dbdimp.c:(.text+0x10e3): undefined reference to
`_OCINlsCharSetIdToName
'
dbdimp.o:dbdimp.c:(.text+0x110f): undefined reference to
`_OCINlsCharSetIdToName
'
collect2: ld returned 1 exit status
make: *** [blib/arch/auto/DBD/Oracle/Oracle.dll] Error 1</pre>
<p>&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;</p>
<p>[ad#middle_end]</p>
<p><strong>!!! HERE IS THE SOLUTION !!!</strong></p>
<p><strong>Taken from http://cpae.typepad.com/capacity_planning_and_eng/ </strong></p>
<p><strong>Thanks to Erik Squires!</strong></p>
<p>[Quote]</p>
<p><span style="font-size: 17px; font-family: Trebuchet MS;"><span id=":i7" class="VrHWId">undefined reference to `_OCILobGetChunkSize&#8217; </span></span></p>
<p>Several people helped me with a fix, but this text below is thanks to Jerry Reed.  Thanks Jerry!</p>
<p>Please note this problem ONLY occurs under Windows.  If you are running Perl under Unix/Linux/MacOS you should be fine.</p>
<p>Jerry Wrote:</p>
<p>The make of DBD Oracle builds an intermediate lib, liboci.a.  Functions defined in this lib are somehow culled from the appropriate cygwin distro dll by the line that reads:</p>
<p>system(&#8220;dlltool &#8211;input-def oci.def &#8211;output-lib liboci.a&#8221;) at line 235 in Makefile.PL.</p>
<p>But oci.def lacks entries for the two undefined symbols -<br />
_OCILobGetChunkSize</p>
<p>and</p>
<p>_OCINlsCharSetIdToName</p>
<p>(the later is named twice in the linker output).</p>
<p>Strip the leading underscore and insert them into a copy of oci.def. (I inserted them in alpha order, but I do not know if this is really required.)</p>
<p>rm, or use make clean to remove liboci.a and cause it to be rebuilt.</p>
<p>perl Makefile.PL<br />
make</p>
<p>You should get no unresolved symbols now.  You can check that liboci.a now contains the correct entries by:</p>
<p>nm liboci.a | egrep -i &#8216;(chunk|nls)&#8217;</p>
<p>[/Quote]</p>
<p>[ad#middle_end] </p>
]]></content:encoded>
			<wfw:commentRss>http://usestrict.net/2009/01/dbdoracle-cygwin-error-during-make/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

