<?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>Freelance PHP Developer &#124; PHP Freelancer</title>
	<atom:link href="http://freelance-php-developer.phpmysql.co.za/feed/" rel="self" type="application/rss+xml" />
	<link>http://freelance-php-developer.phpmysql.co.za</link>
	<description>Johannesburg &#124; CapeTown &#124; Durban</description>
	<lastBuildDate>Mon, 26 Mar 2012 07:41:38 +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>Freelance PHP Developer</title>
		<link>http://freelance-php-developer.phpmysql.co.za/2011/05/experienced-php-developer-available-for-contract-positions/</link>
		<comments>http://freelance-php-developer.phpmysql.co.za/2011/05/experienced-php-developer-available-for-contract-positions/#comments</comments>
		<pubDate>Fri, 13 May 2011 11:23:25 +0000</pubDate>
		<dc:creator>admin</dc:creator>
		
		<guid isPermaLink="false">http://freelance-php-developer.phpmysql.co.za/?p=108</guid>
		<description><![CDATA[If you are looking for an experienced PHP Developer to take up you new or abandoned project , your search is over. I am an experienced developer with my own transport and will come to you for an initial no obligation face to face meeting. I am also considering fulltime employment with salary offers exceeding [...]]]></description>
			<content:encoded><![CDATA[<h2><span style="color: #19d021;"><strong> If you are looking for an experienced PHP Developer to take up you new or abandoned project , your search is over.</strong></span></h2>
<h2><span style="color: #19d021;"><strong>I am an experienced developer with my own transport and will come to you for an initial no obligation face to face meeting.</strong></span></h2>
<h2><span style="color: #19d021;"><strong>I am also considering fulltime employment with salary offers exceeding R35K.</strong></span></h2>
<h2><span style="color: #19d021;"><strong>CallÂ  / SMS me on 079 9111 855 </strong></span></h2>
<h2><span style="color: #19d021;"><strong>Email info@mydeveloper.co.za. </strong></span></h2>
<h2><span style="color: #19d021;"><strong>I will get to you as soon as possible.<br />
</strong></span></h2>
<p><span style="color: #19d021;"> </span><strong> </strong></p>
<p><strong>Brief Profile</strong></p>
<p>I am an innovative, dynamic and self-motivated web/phpÂ  developer with proven solid technical skills in programming, advanced website and web based systems development, deployment and maintenance. I am a resourceful and analytical problem solver, strategic thinker, effective communicator at all levels, both verbally and in writing. I am a natural leader with a yearning passion for quality and success and I quickly acclimatize to new environments</p>
<p><strong>Key Skills</strong></p>
<p><strong>Programming Skills: </strong>PHP,ASP, MVC Frameworks &#8211; Code Igniter , CakePHP ,SOAP , REST , HTML ,Advanced XHTML and CSS , W3C Web Standards, Jquery , Mootools ,Â  Javascript , JSON , Graphic design ,and Photo editing. Proficient user of Dreamweaver CS23/CS4, Photoshop CS3 , Illustrator , Fireworks ,Â  Dreamweaver , Contribute.</p>
<p><strong>Open Source Platforms: </strong>Joomla , Drupal , WordPress , OsCommerce , ZenCart , CubeCart , OpenCart</p>
<p><strong>Web Servers: </strong>Apache Http Server, Apache Tomcat 4.0. , IIS</p>
<p><strong>DBMS: </strong>MySql, MS SQL,</p>
<p><strong>Analysis/Design Methodologies: </strong>UML, OOAD, Unified Modeling Process.</p>
<p><strong>If you require a PHP developer for your project<br />
</strong></p>
<p><strong>please call Mark on 079 9111 855 or email info@mydeveloper.co.za.</strong></p>
]]></content:encoded>
			<wfw:commentRss>http://freelance-php-developer.phpmysql.co.za/2011/05/experienced-php-developer-available-for-contract-positions/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Working as a freelancer</title>
		<link>http://freelance-php-developer.phpmysql.co.za/2010/07/working-as-a-freelancer/</link>
		<comments>http://freelance-php-developer.phpmysql.co.za/2010/07/working-as-a-freelancer/#comments</comments>
		<pubDate>Wed, 28 Jul 2010 04:48:28 +0000</pubDate>
		<dc:creator>admin</dc:creator>
		
		<guid isPermaLink="false">http://freelance-php-developer.phpmysql.co.za/?p=106</guid>
		<description><![CDATA[Freelance work is not for everyone. Freelancing, or working for specific clients on specific projects, comes with distinct advantages and disadvantages. Sometimes people will not know if they are cut out for freelance work until they actually start working. Others may only need to think about a freelance lifestyle to know that it is not [...]]]></description>
			<content:encoded><![CDATA[<p>Freelance work is not for everyone. Freelancing, or working for specific clients on specific projects, comes with distinct advantages and disadvantages. Sometimes people will not know if they are cut out for freelance work until they actually start working. Others may only need to think about a freelance lifestyle to know that it is not for them.</p>
<p>If you are considering freelance work, make sure that you think through the many advantages and disadvantages of freelancing before making any decisions.</p>
<p>Advantages Of Freelance Work<br />
There are many advantages of freelance work. One of the greatest advantages of freelance work is the ability to work from home. No more need for work clothing, commuting time, commuting expenses, sharing an office, working in a cubicle or inane chats during tea breaks.</p>
<p>Another great advantage is the ability to be your own boss. No more being assigned projects you donâ€™t want, having to work with team-mates you donâ€™t respect or worrying about who is looking over your shoulder. Also, freelancing allows you to use a variety of skills on a variety of projects all at the same time. This can be fantastic for individuals who enjoy diverse tasks and topics and work best when they have multiple balls to keep in the air.</p>
<p>Individuals who work well under pressure and are well organised may find freelancing a great idea as they take on all responsibilities for every project, something that is not for the faint of heart!</p>
<p>Disadvantages Of Freelance Work<br />
Freelancing does have its disadvantages as well. One great disadvantage it is that it is a very isolated way to work. When you work from home it is easy to be alone for hours and even days on end. Contact with others often comes in the form of phone calls, faxes or emails so a freelance must often make a point to leave the house and see other people.</p>
<p>Another disadvantage is having to be your own boss. Freelancing can be a nightmare for people who are not good with deadlines, following up on projects, collecting payments or enforcing contract clauses. Also, freelance work necessarily requires a lot of paperwork. Contracts, invoices, client communication, marketing supplies â€“ all of this must be organised and used effectively by a freelance worker. People who are inherently uncomfortable with such organisation often find freelance work a challenge, particularly when it comes to organising a client folder or getting paperwork ready for taxes.</p>
<p>Finally, freelance work is often described as a feast or famine profession. This can make it hard to anticipate weekly, monthly and especially yearly profits, and it can be hard to anticipate when the payments will actually come in. This can be nerve-wracking for many people, so it must be remembered that those who do not enjoy risks may not enjoy freelance work.</p>
<p>There are many advantages and disadvantages to freelance work, just as there are to any other type of job. If you want to learn more about what it is really like to be a freelance worker, contact an individual in your area and see if you can pick their brains or even shadow them for a day. Learning from someone in the trenches is often the best way to decide if freelancing is for you.</p>
]]></content:encoded>
			<wfw:commentRss>http://freelance-php-developer.phpmysql.co.za/2010/07/working-as-a-freelancer/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>CodeIgniter vs. CakePHP</title>
		<link>http://freelance-php-developer.phpmysql.co.za/2010/07/codeigniter-vs-cakephp/</link>
		<comments>http://freelance-php-developer.phpmysql.co.za/2010/07/codeigniter-vs-cakephp/#comments</comments>
		<pubDate>Wed, 28 Jul 2010 04:43:51 +0000</pubDate>
		<dc:creator>admin</dc:creator>
		
		<guid isPermaLink="false">http://freelance-php-developer.phpmysql.co.za/?p=103</guid>
		<description><![CDATA[I almost fear putting this kind of post together as it&#8217;s bound to pull the fanatics (in the negative sense of the word) out of the woodworks. Right off the bat, let me just say that I&#8217;ve tried to be as fair and honest in this assessment and I&#8217;ve tried to keep it just to [...]]]></description>
			<content:encoded><![CDATA[<p>I almost fear putting this kind of post together as it&#8217;s bound to pull the fanatics (in the negative sense of the word) out of the woodworks. Right off the bat, let me just say that I&#8217;ve tried to be as fair and honest in this assessment and I&#8217;ve tried to keep it just to the facts while interjecting what my preferences are.</p>
<p>I&#8217;m pitting these two frameworks against each other but there really isn&#8217;t a clear winner. Each has its strengths and weaknesses and ultimately falls to what your preference for certain features might be.<br />
Why compare these two?</p>
<p>CakePHP and CodeIgniter are quite similar in their approach on a number of things, including their support for PHP4. Any mention of one inevitably leads to someone mentioning the other.</p>
<p>They both attempt to create an MVC architecture which simply means they separate the (data) Model from the Controller (which pulls data from the model to give to the view) from the View (what the user sees).</p>
<p>They both use Routing which takes a URL and maps it to a particular function within a controller (CakePHP calls these actions). CodeIgniter supports regular expressions for routing, whereas you&#8217;ll have to wait until CakePHP 1.2 for that feature. Correction: CakePHP 1.1 supports regular expression for routing but it&#8217;s not detailed in the manual and is getting updated in 1.2.</p>
<p>They both support Scaffolding which is an automated way of generating a view based on the model. Scaffolding is meant for simple prototyping and CodeIgniter takes it a step further by requiring a keyword in the URL to even access the scaffolding. I&#8217;m guessing one could omit the keyword, leaving this feature essentially optional. I prefer not to have to use the keyword as I sometimes build personal projects not intended for public eyes and using a keyword would be a nuisance.</p>
<p>And the list goes on&#8230;<br />
Approach to Simplicity</p>
<p>I believe much of CodeIgniter&#8217;s appeal is its simplicity in its approach. Most of the work is done in the controller, loading in libraries, getting data from the model, and pulling in the view. Everything is in plain sight and you can really see how things work.</p>
<p>CakePHP&#8217;s simplicity comes via automation (euphemistically referred to as &#8220;automagic&#8221;). It makes the coding process quicker but harder to figure out &#8220;what is going on&#8221; without popping your head into the core. For me, I like to understand how everything works and I&#8217;ve had to poke around under the hood more than once. For people just getting started, things probably look a little daunting.<br />
Working with Models</p>
<p>CodeIgniter&#8217;s model handling is fairly straightfoward and basically allows you to mimic a standard SQL query with a few straightforward commands like these examples:</p>
<p>$query = $this->db->getwhere(&#8216;mytable&#8217;, array(id => $id), $limit, $offset);</p>
<p>$this->db->select(&#8216;title&#8217;)->from(&#8216;mytable&#8217;)->where(&#8216;id&#8217;, $id)->limit(10, 20);<br />
$query = $this->db->get();</p>
<p>Note: the method chaining in the second part of this example is only available in PHP5.</p>
<p>You can also create a model object, load it in and build custom methods to handle a custom task. You&#8217;d want to do this in the model and not the controller to help isolate code into the MVC silos.</p>
<p>CakePHP takes a slightly different route by automatically loading in the model that matches the current controller (controllers tend to be named similarly to the models they are associated with). You can turn off this automated loading and even assign different models that should be loaded by the controller instead.</p>
<p>CakePHP also takes things further by establishing all the model associations for you, allowing for some really easy querying. For example, assuming I&#8217;m in a controller named post_controller, I could do the following:</p>
<p>$this->Post->Comment->findAllByPostId($id)</p>
<p>I chose this particular query because it shows two different concepts. The first is the fact that I can access the Comment model via the Post model (assuming I&#8217;ve defined that association in the Post model). The second is the fact that I have a method called findAllByPostId. CakePHP allows records to be grabbed via findByX and findAllByX queries where X is equal to the field name you&#8217;re trying to find.</p>
<p>Where I think Cake shines is in its ability to pull in all associated data automatically. Take the following query as an example:</p>
<p>$this->Post->findById($id)</p>
<p>This query would automatically pull in all the comments associated with this Post. Really handy stuff.<br />
Validation</p>
<p>When working with models, you&#8217;ll inevitably have to handle data validation. Data validation in CodeIgniter is handled via a validation class. A set of rules get defined and assigned to the validation object. The validation object automatically (I assume) validates the data passed via the URL or form. From there, you can decide how that gets handled. The validation class can also help automate some of the process of setting error messages for specific fields.</p>
<p>CakePHP handles its validation through the model itself in one of two ways. The first uses a single test against each field defined in a validate variable declared in the model. This works okay for simple stuff but it quickly becomes a cumbrance. Beyond simple validation, I take advantage of the beforeSave callback to perform any custom validation, invalidating any fields that fail.</p>
<p>It&#8217;s a toss up for me as to which one &#8220;wins&#8221;. CakePHP 1.2 will have its validation system reworked a bit to allow for more flexibility.<br />
Views</p>
<p>CakePHP handles this fairly well by using a default layout (which you can easily switch at runtime). The layout has two variables be default: title_for_layout and content_for_layout. Each action automatically links to a particular view which gets spat into place. Again, it&#8217;s the &#8220;automagic&#8221; approach. As long as you name your files a specific way, controllers automatically get linked to models and views. It&#8217;s easy enough to override all of this, too, and define your own layouts or view files. There&#8217;s no convenient way to get the generated view data, however, making custom built caching mechanisms difficult to implement.</p>
<p>CodeIgniter takes a very straightforward approach: like include files, almost. Each file gets loaded in and processed. There&#8217;s a templating class but it doesn&#8217;t simplify things much beyond the built-in view handling. You can mimic the CakePHP approach by always including the header and footer calls but it&#8217;s not as seamless. CodeIgniter offers hooks allowing view and caching mechanisms to be overridden and replaced with a custom system.<br />
Out of the Box Features</p>
<p>CodeIgniter in my mind wins this hands down with classes for FTP, Email, File Uploading, XMLRPC, Zip encoding and more.</p>
<p>CakePHP on the flip side comes pretty light but tries to make up for it using the Bakery. You can, like CodeIgniter, easily drop in 3rd party classes for any features you might need. Interestingly, although I haven&#8217;t tried it, you could probably drop in many of the CI classes into CakePHP without issue.<br />
Auto-loading</p>
<p>CakePHP allows for application-wide changes to be done via the base application controller that all other controllers inherit from. Likewise, you can create global model methods using the application model file. However, you can fine tune things at the controller level using any of the controller-level callbacks (beforeFilter, afterFilter and beforeRender). Things like auto-loading helpers and components can also be specified easily at the individual controller level.</p>
<p>CodeIgniter allows for the auto-loading of helpers, libraries and plugins but does this application-wide.<br />
Documentation</p>
<p>Documentation is key to understanding any framework well enough to develop within it.</p>
<p>CodeIgniter has a complete list of all components with each method and property documented within. CI also has forums and a wiki which feature a lot of user-submitted code.</p>
<p>CakePHP, on the other hand, isn&#8217;t as well organized. The manual is starting to show its age with some sections not really going much beyond what the API offers. Because of the format of the original documentation, you can also get it in other formats such as CHM and PDF. CakePHP has the Bakery which contains user-submitted articles, components, etc. The dev team also hangs out heavily on the IRC channel (#cakephp at irc.freenode.net). Finally, there&#8217;s the CakePHP Google Group which is pretty active.<br />
Final Verdict</p>
<p>I&#8217;m a pretty pragmatic individual and I honestly feel that these two frameworks have a lot going for them. They take a much simpler approach to application development than the complexity that is something like Symfony.</p>
<p>I&#8217;m still personally a fan of CakePHP over CodeIgniter for much of the &#8220;automagic&#8221; that I mentioned. And it&#8217;s shortcomings have been getting addressed with each new iteration (1.2 will be a considerable leap over 1.1 but it will still be awhile before it&#8217;s released).</p>
]]></content:encoded>
			<wfw:commentRss>http://freelance-php-developer.phpmysql.co.za/2010/07/codeigniter-vs-cakephp/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Facebook Connect User Authentcation</title>
		<link>http://freelance-php-developer.phpmysql.co.za/2010/06/facebook-connect-user-authentcation/</link>
		<comments>http://freelance-php-developer.phpmysql.co.za/2010/06/facebook-connect-user-authentcation/#comments</comments>
		<pubDate>Mon, 14 Jun 2010 06:30:18 +0000</pubDate>
		<dc:creator>admin</dc:creator>
		
		<guid isPermaLink="false">http://freelance-php-developer.phpmysql.co.za/2010/06/facebook-connect-user-authentcation/</guid>
		<description><![CDATA[Step 1. The Setup MySQL Table Letâ€™s begin by creating a database table. CREATE TABLE `users` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `oauth_provider` varchar(10), `oauth_uid` text, `username` text, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1; CREATE TABLE `users` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `oauth_provider` varchar(10), `oauth_uid` text, `username` text, PRIMARY KEY (`id`) [...]]]></description>
			<content:encoded><![CDATA[<h2>Step 1. The Setup</h2>
<h3>MySQL Table</h3>
<p>Letâ€™s begin by creating a database table.</p>
<div>
<div>
<div></div>
</div>
<ol>
<li>CREATE TABLE `users` (</li>
<li> `id` int(10) unsigned NOT NULL AUTO_INCREMENT,</li>
<li> `oauth_provider` varchar(10),</li>
<li> `oauth_uid` text,</li>
<li> `username` text,</li>
<li> PRIMARY KEY (`id`)</li>
<li>) ENGINE=MyISAM  DEFAULT CHARSET=latin1;</li>
</ol>
</div>
<pre>CREATE TABLE `users` (
    `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
    `oauth_provider` varchar(10),
    `oauth_uid` text,
    `username` text,
    PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1;</pre>
<p>Quite simple: we will be setting up a table for user information with  id, username, first and last name, the URL to the userâ€™s picture, and  registered date. Also, weâ€™re adding both an <code>oauth_provider</code> and <code>oauth_uid</code> fields, to distinguish between different  third party open authentication protocols and their identifiers. For  example, letâ€™s say that, next week, you decide that itâ€™s a good idea to  also let Twitter users in. Easy; you just set another value to the oauth<em>provider,  and avoid duplicating oauth</em>uid values.</p>
<h3>The Facebook App</h3>
<p>Letâ€™s begin by <a href="http://www.facebook.com/developers/createapp.php">creating a new  application</a>. Give it a name and agree to the terms and conditions.  Next, grab both the <em>API Key</em> and <em>Secret</em> in the basic  tab as shown below.</p>
<div><img src="http://s3.amazonaws.com/nettuts/708_facebook/fb_basic.png" alt="" width="600" height="235" /></div>
<p>On the canvas tab, set both the <em>Canvas URL</em> and <em>Post-Authorize  Redirect URL</em> to your localhost and path that the script will  process â€” something like <code>http://localhost.com/login_facebook.php?</code>.  Note the question mark at the end and the domain; both are required by  Facebook. Simply set your <code>hosts</code> file to a valid domain  name.</p>
<div><img src="http://s3.amazonaws.com/nettuts/708_facebook/fb_canvas.png" alt="" width="600" height="160" /></div>
<p>On the connect tab, set the Connect URL to the same value and set <code>localhost.com</code> (or the one you are using) as the Base Domain.</p>
<div><img src="http://s3.amazonaws.com/nettuts/708_facebook/fb_connect.png" alt="" width="600" height="180" /></div>
<p>Now save, <a href="http://github.com/facebook/php-sdk/downloads">download  the client library</a>, and unzip <code>facebook.php</code> in the <code>src</code>dir  to a new directory created in the root.</p>
<hr />
<h2>Step 2. The Callback</h2>
<p>The authentication flow has three steps:</p>
<ol>
<li>The local script generates a URL asking the user for permission</li>
<li>Facebook returns to the Canvas URL specified with a GET parameter</li>
<li>The GET parameter authenticates the session</li>
</ol>
<p>Letâ€™s make a quick test before registering and login.</p>
<div>
<div>
<div></div>
</div>
<ol>
<li># We require the library</li>
<li>require(&#8220;facebook.php&#8221;);</li>
<li></li>
<li># Creating the facebook object</li>
<li>$facebook = new Facebook(array(</li>
<li> &#8216;appId&#8217;  =&gt; &#8216;YOUR_APP_ID&#8217;,</li>
<li> &#8216;secret&#8217; =&gt; &#8216;YOUR_APP_SECRET&#8217;,</li>
<li> &#8216;cookie&#8217; =&gt; true</li>
<li>));</li>
<li></li>
<li># Let&#8217;s see if we have an active session</li>
<li>$session = $facebook-&gt;getSession();</li>
<li></li>
<li>if(!empty($session)) {</li>
<li> # Active session, let&#8217;s try getting the user id (getUser()) and user info (api-&gt;(&#8216;/me&#8217;))</li>
<li> try{</li>
<li> $uid = $facebook-&gt;getUser();</li>
<li> $user = $facebook-&gt;api(&#8216;/me&#8217;);</li>
<li> } catch (Exception $e){}</li>
<li></li>
<li> if(!empty($user)){</li>
<li> # User info ok? Let&#8217;s print it (Here we will be adding the login and registering routines)</li>
<li> print_r($user);</li>
<li> } else {</li>
<li> # For testing purposes, if there was an error, let&#8217;s kill the script</li>
<li> die(&#8220;There was an error.&#8221;);</li>
<li> }</li>
<li>} else {</li>
<li> # There&#8217;s no active session, let&#8217;s generate one</li>
<li> $login_url = $facebook-&gt;getLoginUrl();</li>
<li> header(&#8220;Location: &#8220;.$login_url);</li>
<li>}</li>
</ol>
</div>
<pre># We require the library
require("facebook.php");

# Creating the facebook object
$facebook = new Facebook(array(
    'appId'  =&gt; 'YOUR_APP_ID',
    'secret' =&gt; 'YOUR_APP_SECRET',
    'cookie' =&gt; true
));

# Let's see if we have an active session
$session = $facebook-&gt;getSession();

if(!empty($session)) {
    # Active session, let's try getting the user id (getUser()) and user info (api-&gt;('/me'))
    try{
        $uid = $facebook-&gt;getUser();
        $user = $facebook-&gt;api('/me');
    } catch (Exception $e){}

    if(!empty($user)){
        # User info ok? Let's print it (Here we will be adding the login and registering routines)
        print_r($user);
    } else {
        # For testing purposes, if there was an error, let's kill the script
        die("There was an error.");
    }
} else {
    # There's no active session, let's generate one
    $login_url = $facebook-&gt;getLoginUrl();
    header("Location: ".$login_url);
}</pre>
<p>Now, go to <code>http://localhost.com/login_facebook.php</code>, and  letâ€™s see what happens. If you are redirected to Facebook and requested  for permission, we are on the right track.</p>
<div><img src="http://s3.amazonaws.com/nettuts/708_facebook/fb_permission.png" alt="" width="600" height="292" /></div>
<p>However, there might be two issues. The first one: if youâ€™re  redirected to Facebook, but it shows an error, there might be a missing  value in the configuration. Go back to your application settings and  check both the Connect and Canvas tabs and make sure the fields are ok  as described above.</p>
<p>There might be another issue, where you see an error, like â€œUncaught  CurlException: 60: SSL certificate problem, verify that the CA cert is  OK.â€ This happens because of the CURL settings. Youâ€™ll have to open <code>facebook.php</code>,  find the makeRequest() method, and, inside the function, find this  line:</p>
<div>
<div>
<div></div>
</div>
<ol>
<li>$opts = self::$CURL_OPTS;</li>
</ol>
</div>
<pre>$opts = self::$CURL_OPTS;</pre>
<p>Immediately following it, add:</p>
<div>
<div>
<div><a onclick="dp.sh.Toolbar.Command('ViewSource',this);return false;" href="http://net.tutsplus.com/tutorials/php/how-to-authenticate-your-users-with-facebook-connect/#"></a><a onclick="dp.sh.Toolbar.Command('About',this);return false;" href="http://net.tutsplus.com/tutorials/php/how-to-authenticate-your-users-with-facebook-connect/#"></a></div>
</div>
<ol>
<li>$opts[CURLOPT_SSL_VERIFYPEER] = false;</li>
</ol>
</div>
<pre>$opts[CURLOPT_SSL_VERIFYPEER] = false;</pre>
<p>I hate hacking libraries, but I havenâ€™t found another way. Well,  letâ€™s continue with user registration. Iâ€™ve also added a try/catch  statement, because, if thereâ€™s an old session keys in the GET params in  the URL, the script will die with a horrible error.</p>
<hr />
<h2>Step 3. Registration and Authentication</h2>
<p>Weâ€™ll next be working with MySQL. Please note that I will not  implement a data sanitizer, since I want to keep the code as short and  on task as possible. Please keep this in mind: always sanitize your  data.</p>
<p>First, letâ€™s connect to the database.</p>
<div>
<div>
<div><a onclick="dp.sh.Toolbar.Command('ViewSource',this);return false;" href="http://net.tutsplus.com/tutorials/php/how-to-authenticate-your-users-with-facebook-connect/#"></a><a onclick="dp.sh.Toolbar.Command('About',this);return false;" href="http://net.tutsplus.com/tutorials/php/how-to-authenticate-your-users-with-facebook-connect/#"></a></div>
</div>
<ol>
<li>mysql_connect(&#8216;localhost&#8217;, &#8216;YOUR_USERNAME&#8217;, &#8216;YOUR_PASSWORD&#8217;);</li>
<li>mysql_select_db(&#8216;YOUR_DATABASE&#8217;);</li>
</ol>
</div>
<pre>mysql_connect('localhost', 'YOUR_USERNAME', 'YOUR_PASSWORD');
mysql_select_db('YOUR_DATABASE');</pre>
<p>Now, letâ€™s work on the <code>$session</code> conditional, in case we  have a session.</p>
<div>
<div>
<div><a onclick="dp.sh.Toolbar.Command('ViewSource',this);return false;" href="http://net.tutsplus.com/tutorials/php/how-to-authenticate-your-users-with-facebook-connect/#"></a><a onclick="dp.sh.Toolbar.Command('About',this);return false;" href="http://net.tutsplus.com/tutorials/php/how-to-authenticate-your-users-with-facebook-connect/#"></a></div>
</div>
<ol>
<li># We have an active session; let&#8217;s check if we&#8217;ve already registered the user</li>
<li>$query = mysql_query(&#8220;SELECT * FROM users WHERE oauth_provider = &#8216;facebook&#8217; AND oauth_uid = &#8220;. $user['id']);</li>
<li>$result = mysql_fetch_array($query);</li>
<li></li>
<li># If not, let&#8217;s add it to the database</li>
<li>if(empty($result)){</li>
<li> $query = mysql_query(&#8220;INSERT INTO users (oauth_provider, oauth_uid, username) VALUES (&#8216;facebook&#8217;, {$user['id']}, &#8216;{$user['name']}&#8217;)&#8221;);</li>
<li> $query = msyql_query(&#8220;SELECT * FROM users WHERE id = &#8221; . mysql_insert_id());</li>
<li> $result = mysql_fetch_array($query);</li>
<li>}</li>
</ol>
</div>
<pre># We have an active session; let's check if we've already registered the user
$query = mysql_query("SELECT * FROM users WHERE oauth_provider = 'facebook' AND oauth_uid = ". $user['id']);
$result = mysql_fetch_array($query);

# If not, let's add it to the database
if(empty($result)){
    $query = mysql_query("INSERT INTO users (oauth_provider, oauth_uid, username) VALUES ('facebook', {$user['id']}, '{$user['name']}')");
    $query = msyql_query("SELECT * FROM users WHERE id = " . mysql_insert_id());
    $result = mysql_fetch_array($query);
}</pre>
<p>Note that Iâ€™m querying the database, looking for <code>facebook</code> as a <code>oauth_provider</code>; itâ€™s generally a good idea, if you  want to accept other OAuth providers (as twitter, Google Accounts, Open  ID, etc.) and a <code>oauth_uid</code>, since itâ€™s the identifier the  provider gives to its user accounts.</p>
<p>The <code>oauth_provider</code> field could potentially lead to bad  performance if we leave it as a <code>text</code> field type. As such,  the best option is setting it to an <a href="http://dev.mysql.com/doc/refman/5.0/en/enum.html">ENUM type</a>.</p>
<p>We have now a <code>$result</code> var with the values queried from  the database. Letâ€™s next add some sessions. Add this line at the  beginning of your script.</p>
<div>
<ol>
<li>session_start();</li>
</ol>
</div>
<pre>session_start();</pre>
<p>After the <code>empty($result)</code> conditional, append the  following:</p>
<div>
<div>
<div><a onclick="dp.sh.Toolbar.Command('ViewSource',this);return false;" href="http://net.tutsplus.com/tutorials/php/how-to-authenticate-your-users-with-facebook-connect/#"></a><a onclick="dp.sh.Toolbar.Command('About',this);return false;" href="http://net.tutsplus.com/tutorials/php/how-to-authenticate-your-users-with-facebook-connect/#"></a></div>
</div>
<ol>
<li>if(!empty($user)){</li>
<li> # &#8230;</li>
<li></li>
<li> if(empty($result)){</li>
<li> # &#8230;</li>
<li> }</li>
<li></li>
<li> # let&#8217;s set session values</li>
<li> $_SESSION['id'] = $result['id'];</li>
<li> $_SESSION['oauth_uid'] = $result['oauth_uid'];</li>
<li> $_SESSION['oauth_provider'] = $result['oauth_provider'];</li>
<li> $_SESSION['username'] = $result['username'];</li>
<li>}</li>
</ol>
</div>
<pre>if(!empty($user)){
    # ...

    if(empty($result)){
        # ...
    }

    # let's set session values
    $_SESSION['id'] = $result['id'];
    $_SESSION['oauth_uid'] = $result['oauth_uid'];
    $_SESSION['oauth_provider'] = $result['oauth_provider'];
    $_SESSION['username'] = $result['username'];
}</pre>
<p>As it makes little sense to authenticate a user who is already logged  in, just below the <code>session_start()</code> line, add:</p>
<div>
<div>
<div><a onclick="dp.sh.Toolbar.Command('ViewSource',this);return false;" href="http://net.tutsplus.com/tutorials/php/how-to-authenticate-your-users-with-facebook-connect/#"></a><a onclick="dp.sh.Toolbar.Command('About',this);return false;" href="http://net.tutsplus.com/tutorials/php/how-to-authenticate-your-users-with-facebook-connect/#"></a></div>
</div>
<ol>
<li>if(!empty($_SESSION)){</li>
<li> header(&#8220;Location: home.php&#8221;);</li>
<li>}</li>
</ol>
</div>
<pre>if(!empty($_SESSION)){
    header("Location: home.php");
}</pre>
<p>And in the scripts which require authentication, just add:</p>
<div>
<div>
<div><a onclick="dp.sh.Toolbar.Command('ViewSource',this);return false;" href="http://net.tutsplus.com/tutorials/php/how-to-authenticate-your-users-with-facebook-connect/#"></a><a onclick="dp.sh.Toolbar.Command('About',this);return false;" href="http://net.tutsplus.com/tutorials/php/how-to-authenticate-your-users-with-facebook-connect/#"></a></div>
</div>
<ol>
<li>session_start();</li>
<li>if(!empty($_SESSION)){</li>
<li> header(&#8220;Location: login_facebook.php&#8221;);</li>
<li>}</li>
</ol>
</div>
<pre>session_start();
if(!empty($_SESSION)){
    header("Location: login_facebook.php");
}</pre>
<p>And if you want to display the username, access it as an array.</p>
<div>
<div>
<div><a onclick="dp.sh.Toolbar.Command('ViewSource',this);return false;" href="http://net.tutsplus.com/tutorials/php/how-to-authenticate-your-users-with-facebook-connect/#"></a><a onclick="dp.sh.Toolbar.Command('About',this);return false;" href="http://net.tutsplus.com/tutorials/php/how-to-authenticate-your-users-with-facebook-connect/#"></a></div>
</div>
<ol>
<li>echo &#8216;Welcome &#8216; . $_SESSION['username'];</li>
<li># or..</li>
<li>echo &#8216;Welcome &#8216; . !empty($_SESSION) ? $_SESSION['username'] : &#8216;guest&#8217;;</li>
</ol>
</div>
<pre>echo 'Welcome ' . $_SESSION['username'];
# or..
echo 'Welcome ' . !empty($_SESSION) ? $_SESSION['username'] : 'guest';</pre>
<hr />
<h2>Step 4. Additional Methods</h2>
<p>Facebook has a ton of connect features, but here are four that Iâ€™ve  found to be the most useful.</p>
<h3>Legacy Methods</h3>
<p>I might be missing something, but the FQL seems more flexible and  easy than the Graph API. Fortunately, Facebook still lets developers use  it, altough with the new library, it has changed a bit.</p>
<p>If you want the user id, first name, last name, squared thumbnail for  the user picture, the biggest user picture available, and his or her  gender, you can use the <code>users.getInfo</code> method.</p>
<div>
<div>
<div><a onclick="dp.sh.Toolbar.Command('ViewSource',this);return false;" href="http://net.tutsplus.com/tutorials/php/how-to-authenticate-your-users-with-facebook-connect/#"></a><a onclick="dp.sh.Toolbar.Command('About',this);return false;" href="http://net.tutsplus.com/tutorials/php/how-to-authenticate-your-users-with-facebook-connect/#"></a></div>
</div>
<ol>
<li>$uid = $facebook-&gt;getUser();</li>
<li>$api_call = array(</li>
<li> &#8216;method&#8217; =&gt; &#8216;users.getinfo&#8217;,</li>
<li> &#8216;uids&#8217; =&gt; $uid,</li>
<li> &#8216;fields&#8217; =&gt; &#8216;uid, first_name, last_name, pic_square, pic_big, sex&#8217;</li>
<li>);</li>
<li>$users_getinfo = $facebook-&gt;api($api_call);</li>
</ol>
</div>
<pre>    $uid = $facebook-&gt;getUser();
    $api_call = array(
        'method' =&gt; 'users.getinfo',
        'uids' =&gt; $uid,
        'fields' =&gt; 'uid, first_name, last_name, pic_square, pic_big, sex'
    );
    $users_getinfo = $facebook-&gt;api($api_call);</pre>
<p>You can check <a href="http://wiki.developers.facebook.com/index.php/Users.getInfo#Response">the  full list of fields available for Users.getInfo</a>.</p>
<p>It is possible to achieve the same result, using FQL.</p>
<div>
<div>
<div><a onclick="dp.sh.Toolbar.Command('ViewSource',this);return false;" href="http://net.tutsplus.com/tutorials/php/how-to-authenticate-your-users-with-facebook-connect/#"></a><a onclick="dp.sh.Toolbar.Command('About',this);return false;" href="http://net.tutsplus.com/tutorials/php/how-to-authenticate-your-users-with-facebook-connect/#"></a></div>
</div>
<ol>
<li>$uid = $facebook-&gt;getUser();</li>
<li>$fql_query  =   array(</li>
<li> &#8216;method&#8217; =&gt; &#8216;fql.query&#8217;,</li>
<li> &#8216;query&#8217; =&gt; &#8216;SELECT uid, first_name, last_name, pic_square, pic_big, sex FROM user WHERE uid = &#8216; . $uid</li>
<li>);</li>
<li>$fql_info = $facebook-&gt;api($fql_query);</li>
</ol>
</div>
<pre>    $uid = $facebook-&gt;getUser();
    $fql_query  =   array(
        'method' =&gt; 'fql.query',
        'query' =&gt; 'SELECT uid, first_name, last_name, pic_square, pic_big, sex FROM user WHERE uid = ' . $uid
    );
    $fql_info = $facebook-&gt;api($fql_query);</pre>
<p>Hereâ€™s the <a href="http://developers.facebook.com/docs/reference/fql/">list of tables</a> which can be accessed with FQL, as well as <a href="http://developers.facebook.com/docs/reference/fql/user">the fields  available for the table users</a>.</p>
<h3>Extended Permissions</h3>
<p>Facebook provides applications with some interaction with the userâ€™s  data â€“ just as long as itâ€™s authorized. With the old API, the  authorization for additional permissions was exclusively available for  the Javascript SDK (altough Iâ€™m not quite sure). With the new API, we  can easily redirect the user to an authorization dialog in Facebook, and  return to our site after the access is either granted or denied.</p>
<p>In the following example, we will be redirecting a user to authorize  posts status updates, photos, videos and notes, the userâ€™s real email  address, birthday and access to photos and videos.</p>
<div>
<div>
<div><a onclick="dp.sh.Toolbar.Command('ViewSource',this);return false;" href="http://net.tutsplus.com/tutorials/php/how-to-authenticate-your-users-with-facebook-connect/#"></a><a onclick="dp.sh.Toolbar.Command('About',this);return false;" href="http://net.tutsplus.com/tutorials/php/how-to-authenticate-your-users-with-facebook-connect/#"></a></div>
</div>
<ol>
<li>$uid = $facebook-&gt;getUser();</li>
<li></li>
<li># req_perms is a comma separated list of the permissions needed</li>
<li>$url = $facebook-&gt;getLoginUrl(array(</li>
<li> &#8216;req_perms&#8217; =&gt; &#8216;email,user_birthday,status_update,publish_stream,user_photos,user_videos&#8217;</li>
<li>));</li>
<li>header(&#8220;Location: {$url} &#8220;);</li>
</ol>
</div>
<pre>$uid = $facebook-&gt;getUser();

# req_perms is a comma separated list of the permissions needed
$url = $facebook-&gt;getLoginUrl(array(
    'req_perms' =&gt; 'email,user_birthday,status_update,publish_stream,user_photos,user_videos'
));
header("Location: {$url} ");</pre>
<p>Hereâ€™s <a href="http://developers.facebook.com/docs/authentication/permissions">a  full list of permissions</a>. Note that you can specify both the url to  direct to if the user accepts and the url to be redirected to if the  user denies. The key for these array elements are <code>next</code> and <code>cancel_url</code>,  respectively. Hereâ€™s a quick example:</p>
<div>
<div>
<div><a onclick="dp.sh.Toolbar.Command('ViewSource',this);return false;" href="http://net.tutsplus.com/tutorials/php/how-to-authenticate-your-users-with-facebook-connect/#"></a><a onclick="dp.sh.Toolbar.Command('About',this);return false;" href="http://net.tutsplus.com/tutorials/php/how-to-authenticate-your-users-with-facebook-connect/#"></a></div>
</div>
<ol>
<li>$url = $facebook-&gt;getLoginUrl(array(</li>
<li> &#8216;req_perms&#8217; =&gt; &#8216;email&#8217;,</li>
<li> &#8216;next&#8217; =&gt; &#8216;http://localhost.com/thanks.php&#8217;,</li>
<li> &#8216;cancel_url&#8217; =&gt; &#8216;http://localhost.com/sorry.php&#8217;</li>
<li>));</li>
</ol>
</div>
<pre>$url = $facebook-&gt;getLoginUrl(array(
    'req_perms' =&gt; 'email',
    'next' =&gt; 'http://localhost.com/thanks.php',
    'cancel_url' =&gt; 'http://localhost.com/sorry.php'
));</pre>
<p>If not specified, the default is the requesting scriptâ€™s location.</p>
<div><img src="http://s3.amazonaws.com/nettuts/708_facebook/fb_additional_permissions.png" alt="" width="600" height="478" /></div>
<h3>Checking for Extended Permissions</h3>
<p>Since the user can easily revoke permissions, the application should  always check if a given permission is granted before using it, specially  if itâ€™s about publishing something. We will have to use the legacy API,  as <a href="http://forum.developers.facebook.com/viewtopic.php?id=58565">it  seems itâ€™s not fully implemented with the new one yet</a>.</p>
<div>
<div>
<div><a onclick="dp.sh.Toolbar.Command('ViewSource',this);return false;" href="http://net.tutsplus.com/tutorials/php/how-to-authenticate-your-users-with-facebook-connect/#"></a><a onclick="dp.sh.Toolbar.Command('About',this);return false;" href="http://net.tutsplus.com/tutorials/php/how-to-authenticate-your-users-with-facebook-connect/#"></a></div>
</div>
<ol>
<li>$uid = $facebook-&gt;getUser();</li>
<li></li>
<li># users.hasAppPermission</li>
<li>$api_call = array(</li>
<li> &#8216;method&#8217; =&gt; &#8216;users.hasAppPermission&#8217;,</li>
<li> &#8216;uid&#8217; =&gt; $uid,</li>
<li> &#8216;ext_perm&#8217; =&gt; &#8216;publish_stream&#8217;</li>
<li>);</li>
<li>$users_hasapppermission = $facebook-&gt;api($api_call);</li>
<li>print_r($users_hasapppermission);</li>
</ol>
</div>
<pre>    $uid = $facebook-&gt;getUser();

    # users.hasAppPermission
    $api_call = array(
        'method' =&gt; 'users.hasAppPermission',
        'uid' =&gt; $uid,
        'ext_perm' =&gt; 'publish_stream'
    );
    $users_hasapppermission = $facebook-&gt;api($api_call);
    print_r($users_hasapppermission);</pre>
<p>The <code>ext_perm</code> will only support <a href="http://developers.facebook.com/docs/reference/rest/users.hasAppPermission">the  old list of available permissions</a>.</p>
<h3>Publishing to the Wall</h3>
<p>Letâ€™s post something to the wall after verifying the user has the <code>publish_stream</code> permission.</p>
<div>
<div>
<div><a onclick="dp.sh.Toolbar.Command('ViewSource',this);return false;" href="http://net.tutsplus.com/tutorials/php/how-to-authenticate-your-users-with-facebook-connect/#"></a><a onclick="dp.sh.Toolbar.Command('About',this);return false;" href="http://net.tutsplus.com/tutorials/php/how-to-authenticate-your-users-with-facebook-connect/#"></a></div>
</div>
<ol>
<li># let&#8217;s check if the user has granted access to posting in the wall</li>
<li>$api_call = array(</li>
<li> &#8216;method&#8217; =&gt; &#8216;users.hasAppPermission&#8217;,</li>
<li> &#8216;uid&#8217; =&gt; $uid,</li>
<li> &#8216;ext_perm&#8217; =&gt; &#8216;publish_stream&#8217;</li>
<li>);</li>
<li>$can_post = $facebook-&gt;api($api_call);</li>
<li>if($can_post){</li>
<li> # post it!</li>
<li> $facebook-&gt;api(&#8216;/&#8217;.$uid.&#8217;/feed&#8217;, &#8216;post&#8217;, array(&#8216;message&#8217; =&gt; &#8216;Saying hello from my Facebook app!&#8217;));</li>
<li> echo &#8216;Posted!&#8217;;</li>
<li>} else {</li>
<li> die(&#8216;Permissions required!&#8217;);</li>
<li>}</li>
</ol>
</div>
<pre>    # let's check if the user has granted access to posting in the wall
    $api_call = array(
        'method' =&gt; 'users.hasAppPermission',
        'uid' =&gt; $uid,
        'ext_perm' =&gt; 'publish_stream'
    );
    $can_post = $facebook-&gt;api($api_call);
    if($can_post){
        # post it!
        $facebook-&gt;api('/'.$uid.'/feed', 'post', array('message' =&gt; 'Saying hello from my Facebook app!'));
        echo 'Posted!';
    } else {
        die('Permissions required!');
    }</pre>
<p>Essentially, we are making an API call to <code>/&lt;user_id&gt;/feed</code>,  using the POST method (second argument) and an array as a third  argument for the data to be sent. In this case, this third argument  supports <code>message</code>, <code>link</code>, <code>picture</code>, <code>caption</code>,  <code>name</code> and <code>description</code>. Hereâ€™s the code:</p>
<div>
<div>
<div><a onclick="dp.sh.Toolbar.Command('ViewSource',this);return false;" href="http://net.tutsplus.com/tutorials/php/how-to-authenticate-your-users-with-facebook-connect/#"></a><a onclick="dp.sh.Toolbar.Command('About',this);return false;" href="http://net.tutsplus.com/tutorials/php/how-to-authenticate-your-users-with-facebook-connect/#"></a></div>
</div>
<ol>
<li>$facebook-&gt;api(&#8216;/&#8217;.$uid.&#8217;/feed&#8217;, &#8216;post&#8217;, array(</li>
<li> &#8216;message&#8217; =&gt; &#8216;The message&#8217;,</li>
<li> &#8216;name&#8217; =&gt; &#8216;The name&#8217;,</li>
<li> &#8216;description&#8217; =&gt; &#8216;The description&#8217;,</li>
<li> &#8216;caption&#8217; =&gt; &#8216;The caption&#8217;,</li>
<li> &#8216;picture&#8217; =&gt; &#8216;http://i.imgur.com/yx3q2.png&#8217;,</li>
<li> &#8216;link&#8217; =&gt; &#8216;http://net.tutsplus.com/&#8217;</li>
<li>));</li>
</ol>
</div>
<pre>$facebook-&gt;api('/'.$uid.'/feed', 'post', array(
    'message' =&gt; 'The message',
    'name' =&gt; 'The name',
    'description' =&gt; 'The description',
    'caption' =&gt; 'The caption',
    'picture' =&gt; 'http://i.imgur.com/yx3q2.png',
    'link' =&gt; 'http://net.tutsplus.com/'
));</pre>
<p>Hereâ€™s how it is posted.</p>
<div><img src="http://s3.amazonaws.com/nettuts/708_facebook/fb_wall.png" alt="" width="600" height="140" /></div>
<h3>Some Additional Information you Should Know:</h3>
<p>The user can easily revoke permissions with two clicks in his or her  wall. You should heavily test what might happen if a user revoked one or  more permissions that are vital for the proper functioning of your  website, or even if the application is fully removed. This is important.</p>
<ul>
<li>In <a href="http://www.facebook.com/editapps.php">Application  Settings</a> you can remove the application entirely by clicking the x  at the right side.</li>
<li>You can remove permissions individually in the <a href="http://www.facebook.com/editapps.php?v=extended">Granted  Additional Permissions</a> section.</li>
</ul>
<hr />
<h2>5. Conclusion</h2>
<p>While Facebookâ€™s authentication capabilities are indeed useful, since  so many people are on Facebook these days, using it as the only method  of authentication in a site is not recommended. What about those who  donâ€™t have Facebook accounts? Are they not allowed to access your  application? Thanks for reading!</p>
]]></content:encoded>
			<wfw:commentRss>http://freelance-php-developer.phpmysql.co.za/2010/06/facebook-connect-user-authentcation/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>MVC Basics for beginners</title>
		<link>http://freelance-php-developer.phpmysql.co.za/2010/06/mvc-basics-for-beginners/</link>
		<comments>http://freelance-php-developer.phpmysql.co.za/2010/06/mvc-basics-for-beginners/#comments</comments>
		<pubDate>Mon, 14 Jun 2010 06:20:48 +0000</pubDate>
		<dc:creator>admin</dc:creator>
		
		<guid isPermaLink="false">http://freelance-php-developer.phpmysql.co.za/?p=87</guid>
		<description><![CDATA[MVC for Beginners Tutorial Details Difficulty: Beginner Architecture: MVC Model-View-Controller (MVC) is probably one of the most quoted patterns in the web programming world in recent years. Anyone currently working in anything related to web application development will have heard or read the acronym hundreds of times. Today, weâ€™ll clarify what MVC means, and why [...]]]></description>
			<content:encoded><![CDATA[<p><!-- Post Title --></p>
<h1>MVC for Beginners</h1>
<div><!-- [END] Social Media --></p>
<div>
<h5>Tutorial Details</h5>
<ul>
<li><strong>Difficulty: </strong> Beginner</li>
<li><strong>Architecture: </strong> MVC</li>
</ul>
</div>
</div>
<p>Model-View-Controller (MVC) is probably one of the most quoted  patterns in the web programming world in recent years. Anyone currently  working in anything related to web application development will have  heard or read the acronym hundreds of times. Today, weâ€™ll clarify what  MVC means, and why it has become so popular.</p>
<hr />
<h2>Ancient Historyâ€¦</h2>
<blockquote><p>
MVC is not a design pattern, it is an Architectural  pattern that describes a way to structure our application and the  responsibilities and interactions for each part in that structure.
</p></blockquote>
<p>It was first described in 1979 and, obviously, the context was a  little bit different. The concept of web application did not exist. Tim  Berners Lee sowed the seeds of World Wide Web in the early nineties and  changed the world forever. The pattern we use today for web development  is an adaptation of the original pattern.</p>
<p>The wild popularization of this structure for web applications is due  to its inclusion in two development frameworks that have become  immensely popular: Struts and Ruby on Rails. These two environments  marked the way for the hundreds of frameworks created later.</p>
<div><img src="http://s3.amazonaws.com/nettuts/613_mvc/frameworks.jpg" border="0" alt="" /></div>
<hr />
<h2>MVC for Web Applications</h2>
<p>The idea behind the Model-View-Controller architectural pattern is  simple: we must have the following responsibilities clearly separated in  our application:</p>
<div><img src="http://s3.amazonaws.com/nettuts/613_mvc/components.jpg" border="0" alt="" /></div>
<p>The application is divided into these three main components, each one  in charge of different tasks. Letâ€™s see a detailed explanation and an  example.</p>
<h3>Controller</h3>
<p>The <strong>Controller</strong> manages the user requests (received  as HTTP GET or POST requests when the user clicks on GUI elements to  perform actions). Its main function is to call and coordinate the  necessary resources/objects needed to perform the user action. Usually  the controller will call the appropriate model for the task and then  selects the proper view.</p>
<h3>Model</h3>
<p>The <strong>Model</strong> is the data and the rules applying to that  data, which represent concepts that the application manages. In any  software system, everything is modeled as data that we handle in a  certain way. What is a user, a message or a book for an application?  Only data that must be handled according to specific rules (date can not  be in the future, e-mail must have a specific format, name cannot be  more than x characters long, etc).</p>
<div><img src="http://s3.amazonaws.com/nettuts/613_mvc/ModelData.jpg" border="0" alt="" /></div>
<p>The model gives the controller a data representation of whatever the  user requested (a message, a list of books, a photo album, etc). This  data model will be the same no matter how we may want to present it to  the user, thatâ€™s why we can choose any available view to render it.</p>
<p>The model contains the most important part of our application logic,  the logic that applies to the problem we are dealing with (a forum, a  shop, a bank, etc). The controller contains a more  internal-organizational logic for the application itself (more like  housekeeping).</p>
<h3>View</h3>
<p>The <strong>View</strong> provides different ways to present the data  received from the model. They may be templates where that data is  filled. There may be several different views and the controller has to  decide which one to use.</p>
<p>A web application is usually composed of a set of controllers, models  and views. The controller may be structured as a main controller that  receives all requests and calls specific controllers that handles  actions for each case.</p>
<hr />
<h2>Letâ€™s See an Example</h2>
<p>Suppose weâ€™re developing an online book store. The user can perform  actions such as: view books, register, buy, add items to current order,  create or delete books (if he is an administrator, etc.). Letâ€™s see what  happens when the user clicks on the <em>fantasy</em> category to view  the titles we have available.</p>
<p>We will have a particular controller to handle all books-related  actions (view, edit, create, etc). Letâ€™s call it books_controller.php  for this example. We will also have a model, for example book_model.php,  handling data and logic related to the items in the shop. Finally we  will have a series of views to present, for example, a list of books, a  page to edit books, etc.</p>
<p>The following figure shows how the user request to view the fantasy  books list is handled:</p>
<div><img src="http://s3.amazonaws.com/nettuts/613_mvc/diagram.jpg" border="0" alt="" /></div>
<p>The controller (books_controller.php) receives the user request [1]  as an HTTP GET or POST request (we can also have a central controller,  for example index.php receiving it and then calling  books_controller.php).</p>
<p>The controller examines the request and the parameters and calls the  model (book_model.php) <em>asking</em> him to return the list of  available fantasy books [2].</p>
<p>The model is responsible for getting that information from the  database (or wherever it is stored) [3], apply filters or logic if  necessary, and return the data representing the list of books [4].</p>
<p>The controller will use the appropriate view [5] to present these  data to the user [6-7]. If the request came from a mobile phone, a view  for mobile phones will be used, if the user has a particular skin  selected, the corresponding view will be chosen, and so on.</p>
<hr />
<h2>What are the Advantages?</h2>
<blockquote><p>
The most obvious advantage we gain using MVC is a clear  separation of presentation (the interface with the user) and application  logic.
</p></blockquote>
<p>Support for different types of users using different types of devices  is a common problem these days. The interface presented must be  different if the request came from a desktop computer or from a cell  phone. The model returns exactly the same data, the only difference is  that the controller will choose a different view to render them (we can  think of a different template).</p>
<p>Apart from isolating the view from the business logic, the M-V-C  separation reduces the complexity when designing large applications. The  code is much more structured and therefore easier maintain, test and  reuse.</p>
<hr />
<h2>Ok, but Why a Framework?</h2>
<p>When you use a framework, the basic structure for MVC is already  prepared and you just have to extend that structure, placing your files  in the appropriate directory, to comply with the Model-View-Controller  pattern. Also you get a lot of functionality already written and  thoroughly tested.</p>
<p>Take cakePHP as an example MVC framework. Once you have it installed,  youâ€™ll see three main directories:</p>
<ul>
<li>app/</li>
<li>cake/</li>
<li>vendors/</li>
</ul>
<p>The <strong>app</strong> folder is where you place your files. It is  your place to develop your part of the application.</p>
<p>The <strong>cake</strong> folder is where cakePHP has its files and  where they have developed their part (main framework functionality).</p>
<p>The <strong>vendors</strong> folder is for third-party PHP libraries  if needed.</p>
<p>Your working place (app directory) has the following structure:</p>
<ul>
<li>app/
<ul>
<li>config/</li>
<li>controllers/</li>
<li>locale/</li>
<li>models/</li>
<li>plugins/</li>
<li>tests/</li>
<li>tmp/</li>
<li>vendors/</li>
<li>views/</li>
<li>webroot/</li>
</ul>
</li>
</ul>
<p>Now you have to put your controllers in the <strong>controllers</strong> directory, your models in the <strong>models</strong> directory and  your views inâ€¦ the <strong>views</strong> directory!</p>
<p>Once you get used to your framework, youâ€™ll be able to know where to  look for almost any piece of code you need to modify or create. This  organization alone makes maintainability a lot easier.</p>
<hr />
<h2>Letâ€™s Framework our Example</h2>
<p>Since this tutorial is not intended to show you how to create an  application using cakePHP, weâ€™ll use it only to show example code for  the model, view and controller components and comment on the benefits of  using an MVC framework. The code is oversimplified and not suitable for  real applications.</p>
<p>Remember we had a book store and a curious user who wants to see the  complete list of books in the <em>fantasy</em> category. We said that  the controller will be the one receiving the request and coordinating  the necessary actions.</p>
<p>So, when the user clicks, the browser will be requesting this url:</p>
<div>
<ol>
<li>www.ourstore.com/books/list/fantasy</li>
</ol>
</div>
<pre> www.ourstore.com/books/list/fantasy</pre>
<p>CakePHP likes to format URLs in the form  /controller/action/param1/param2 , where <em>action</em> is the function  to call within the controller. In the old classic url format it would  be:</p>
<div>
<div>
<div><a onclick="dp.sh.Toolbar.Command('ViewSource',this);return false;" href="http://net.tutsplus.com/tutorials/other/mvc-for-noobs/#"></a><a onclick="dp.sh.Toolbar.Command('About',this);return false;" href="http://net.tutsplus.com/tutorials/other/mvc-for-noobs/#"></a></div>
</div>
<ol>
<li>www.ourstore.com/books_controller.php?action=list&amp;category=fantasy</li>
</ol>
</div>
<pre> www.ourstore.com/books_controller.php?action=list&amp;category=fantasy</pre>
<h3>Controller</h3>
<p>With the help of cakePHP framework, our controller will look  something like this:</p>
<div>
<div>
<div><a onclick="dp.sh.Toolbar.Command('ViewSource',this);return false;" href="http://net.tutsplus.com/tutorials/other/mvc-for-noobs/#"></a><a onclick="dp.sh.Toolbar.Command('About',this);return false;" href="http://net.tutsplus.com/tutorials/other/mvc-for-noobs/#"></a></div>
</div>
<ol>
<li>&lt;?php</li>
<li></li>
<li>class BooksController extends AppController {</li>
<li></li>
<li> function list($category) {</li>
<li></li>
<li> $this-&gt;set(&#8216;books&#8217;, $this-&gt;Book-&gt;findAllByCategory($category));</li>
<li></li>
<li> }</li>
<li></li>
<li> function add() { &#8230; &#8230; }</li>
<li></li>
<li> function delete() { &#8230; &#8230; }</li>
<li></li>
<li> &#8230; &#8230; } ?&gt;</li>
</ol>
</div>
<pre>&lt;?php

class BooksController extends AppController {

 function list($category) {

 $this-&gt;set('books', $this-&gt;Book-&gt;findAllByCategory($category));

 }

 function add() { ... ... }

 function delete() { ... ... }

 ... ... } ?&gt;</pre>
<p>Simple, isnâ€™t it?. This controller will be saved as  books_controller.php and placed in /app/controllers. It contains the  list function, to perform the action in our example, but also other  functions to perform other book-related actions (add a new book, delete a  new book, etc).</p>
<p>The framework provides a lot of things for us and only one line is  necessary to list the books. We have base classes with the basic  controller behavior already defined, so we inherit from them  (AppController which inherits from Controller).</p>
<p>All it has to do in the list action is call the model to get the data  and then choose a view to present it to the user. Letâ€™s explain how  this is done.</p>
<p><em>this-&gt;Book</em> is our Model, and this part:</p>
<div>
<div>
<div><a onclick="dp.sh.Toolbar.Command('ViewSource',this);return false;" href="http://net.tutsplus.com/tutorials/other/mvc-for-noobs/#"></a><a onclick="dp.sh.Toolbar.Command('About',this);return false;" href="http://net.tutsplus.com/tutorials/other/mvc-for-noobs/#"></a></div>
</div>
<ol>
<li>$this-&gt;Book-&gt;findAllByCategory($category)</li>
</ol>
</div>
<pre> $this-&gt;Book-&gt;findAllByCategory($category)</pre>
<p>is telling the model to return the list of books in the selected  category (weâ€™ll see the model later).</p>
<p>The <em>set</em> method in the line:</p>
<div>
<div>
<div><a onclick="dp.sh.Toolbar.Command('ViewSource',this);return false;" href="http://net.tutsplus.com/tutorials/other/mvc-for-noobs/#"></a><a onclick="dp.sh.Toolbar.Command('About',this);return false;" href="http://net.tutsplus.com/tutorials/other/mvc-for-noobs/#"></a></div>
</div>
<ol>
<li>$this-&gt;set(&#8216;books&#8217;, $this-&gt;Book-&gt;findAllByCategory($category));</li>
</ol>
</div>
<pre> $this-&gt;set('books', $this-&gt;Book-&gt;findAllByCategory($category));</pre>
<p>Is the controller way to pass data to the view. It sets the <em>books</em> variable to the data returned by the model and makes it accessible to  the view.</p>
<p>Now we just have to render the view, but this will be done  automatically by cakePHP if we want the default view. If we need any  other view we just have to call it explicitly using the <em>render</em> method.</p>
<h3>Model</h3>
<p>The model is even more simple:</p>
<div>
<div>
<div><a onclick="dp.sh.Toolbar.Command('ViewSource',this);return false;" href="http://net.tutsplus.com/tutorials/other/mvc-for-noobs/#"></a><a onclick="dp.sh.Toolbar.Command('About',this);return false;" href="http://net.tutsplus.com/tutorials/other/mvc-for-noobs/#"></a></div>
</div>
<ol>
<li>&lt;?php</li>
<li></li>
<li>class Book extends AppModel {</li>
<li></li>
<li>}</li>
<li></li>
<li>?&gt;</li>
</ol>
</div>
<pre>&lt;?php

class Book extends AppModel { 

}

?&gt;</pre>
<p>Why empty? Because it inherits from a base class that provides  necessary functionality and we have followed the CakePHP name  conventions to allow the framework to do other tasks automatically. For  example, cakePHP knows, based on names, that this model is used in  BooksController and that it will access a database table called books.</p>
<p>With this declaration only we have a book model capable of reading,  deleting or saving data from the database</p>
<p>The code will will be saved as book.php and placed in /app/models.</p>
<h3>View</h3>
<p>All we have to do now is creating a view (at least one) for the list  action. The view will have the HTML code and a few (as few as possible)  PHP lines to loop through the books array provided by the model.</p>
<div>
<div>
<div><a onclick="dp.sh.Toolbar.Command('ViewSource',this);return false;" href="http://net.tutsplus.com/tutorials/other/mvc-for-noobs/#"></a><a onclick="dp.sh.Toolbar.Command('About',this);return false;" href="http://net.tutsplus.com/tutorials/other/mvc-for-noobs/#"></a></div>
</div>
<ol>
<li>&lt;table&gt; &lt;tr&gt; &lt;th&gt;Title&lt;/th&gt; &lt;th&gt;Author&lt;/th&gt; &lt;th&gt;Price&lt;/th&gt; &lt;/tr&gt;</li>
<li></li>
<li>&lt;?php foreach ($books as $book): ?&gt; &lt;tr&gt; &lt;td&gt; &lt;?php echo $book['Book']['title']; ?&gt; &lt;/td&gt; &lt;td&gt; &lt;?php echo $book['Book']['author']; ?&gt; &lt;/td&gt; &lt;td&gt; &lt;?php echo $book['Book']['price']; ?&gt; &lt;/td&gt; &lt;/tr&gt; &lt;?php endforeach; ?&gt;</li>
<li></li>
<li>&lt;/table&gt;</li>
</ol>
</div>
<pre>&lt;table&gt; &lt;tr&gt; &lt;th&gt;Title&lt;/th&gt; &lt;th&gt;Author&lt;/th&gt; &lt;th&gt;Price&lt;/th&gt; &lt;/tr&gt;

&lt;?php foreach ($books as $book): ?&gt; &lt;tr&gt; &lt;td&gt; &lt;?php echo $book['Book']['title']; ?&gt; &lt;/td&gt; &lt;td&gt; &lt;?php echo $book['Book']['author']; ?&gt; &lt;/td&gt; &lt;td&gt; &lt;?php echo $book['Book']['price']; ?&gt; &lt;/td&gt; &lt;/tr&gt; &lt;?php endforeach; ?&gt;

&lt;/table&gt;</pre>
<p>As we can see, the view doesnâ€™t produce a complete page, just an HTML  fragment (a table in this case). This is because CakePHP provides  another way to define the layout of the page, and the views are inserted  into that layout. The framework also provides us with some helper  objects to make common task easy when creating these HTML excerpts  (insert forms, links, Ajax or JavaScript).</p>
<p>We make this the default view saving it as list.ctp ( list is the  name of the action and ctp means cake template) and placing it in  /app/views/books (inside books because these are views for books  controller actions).</p>
<p>And this completes the three components with the help of CakePHP  framework!</p>
<hr />
<h2>Conclusion</h2>
<p>We have learned what is probably the most commonly used architectural  pattern today. We must be aware though that when we talk about patterns  in the programming world, we are talking about flexible frames, to be  tailored to the particular problem at hand. We will find implementations  introducing variations on the structure we have seen, but the important  thing is that, in the end, the pattern helps us gain a clear division  between responsibilities and better maintainability, code-reuse, and  testing.</p>
<p>We have also seen the advantages of using an MVC framework that  provides us with a basic MVC skeleton and a lot of functionality,  improving our productivity and making the development process easier.  Thanks for reading!</p>
]]></content:encoded>
			<wfw:commentRss>http://freelance-php-developer.phpmysql.co.za/2010/06/mvc-basics-for-beginners/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>PHP Developer CodeIgniter MVC Framework</title>
		<link>http://freelance-php-developer.phpmysql.co.za/2010/06/php-developer-codeigniter-mvc-framework/</link>
		<comments>http://freelance-php-developer.phpmysql.co.za/2010/06/php-developer-codeigniter-mvc-framework/#comments</comments>
		<pubDate>Mon, 14 Jun 2010 06:03:53 +0000</pubDate>
		<dc:creator>admin</dc:creator>
		
		<guid isPermaLink="false">http://freelance-php-developer.phpmysql.co.za/?p=81</guid>
		<description><![CDATA[Everything You Need to Get Started With CodeIgniter Tutorial Details Difficulty: Beginner Technology: PHP CodeIgniter is a web application framework for PHP. It enables developers to build web applications faster, and it offers many helpful code libraries and helpers which speed up tedious tasks in PHP. CodeIgniter is based on a modular design; meaning that [...]]]></description>
			<content:encoded><![CDATA[<h1>Everything You Need to Get Started With CodeIgniter</h1>
<div><!-- [END] Social Media --></p>
<div>
<h5>Tutorial Details</h5>
<ul>
<li><strong>Difficulty</strong>: Beginner</li>
<li><strong>Technology</strong>:  PHP</li>
</ul>
</div>
</div>
<p>CodeIgniter is a web application framework for PHP. It enables  developers to build web applications faster, and it offers many helpful  code libraries and helpers which speed up tedious tasks in PHP.  CodeIgniter is based on a modular design; meaning that you can implement  specific libraries at your discretion â€“ which adds to the speed of the  framework. This tutorial will attempt to show you the basics of setting  up the framework, including how to build a basic hello world application  that uses the MVC approach.</p>
<hr />
<h2>Why a Framework?</h2>
<div><img src="http://nettuts.s3.amazonaws.com/180_efficientcode/frameworks.png" alt="Why a Framework?" /></div>
<p>Frameworks allow for structure in developing applications by  providing reusable classes and functions which can reduce development  time significantly. Some downsides to frameworks are that they provide  unwanted classes, adding code bloat which makes the app harder to  navigate.</p>
<hr />
<h2>Why CodeIgniter?</h2>
<div><img src="http://nettuts.s3.amazonaws.com/183_codeIgniter/20090118-180850.png" alt="CodeIgniter Basics" /></div>
<p>CodeIgniter is a very light, well performing framework. While, it is  perfect for a beginner (because<br />
 of the small learning curve), itâ€™s also perfect for large and  demanding web applications. CodeIgniter is developed by EllisLab and has  thorough, easy to understand<br />
 documentation. Below is a list of reasons of what makes CodeIgniter a  smart framework to use?</p>
<ul>
<li> Small footprint with exceptional performance</li>
<li> MVC approach to development (although it is very loosely based  which allows for flexibility)</li>
<li> Generates search engine friendly clean URLs</li>
<li> Easily extensible</li>
<li> Runs on both PHP 4 (4.3.2+) and 5</li>
<li> Support for most major databases including MySQL (4.1+), MySQLi, MS  SQL, Postgres, Oracle, SQLite,<br />
 and ODBC.</li>
<li> Application security is a focus</li>
<li> Easy caching operations</li>
<li> Many libraries and helpers to help you with complex operations such  as email, image manipulation,<br />
 form validation, file uploading, sessions, multilingual apps and  creating apis for your app</li>
<li> Most libraries are only loaded when needed which cuts back on  resources needed</li>
</ul>
<hr />
<h2>Why MVC?</h2>
<div><img src="http://nettuts.s3.amazonaws.com/183_codeIgniter/mvc.png" alt="MVC" /></div>
<p>For starters, MVC stands for Model, View, Controller. It is a  programing pattern used in developing<br />
 web apps. This pattern isolates the user interface and backend (i.e.  database interaction from each other. A successful<br />
 implementation of this lets developers modify their user interface or  backend with out affecting<br />
 the other. MVC also increases the flexibly of an app by being able to  resuse models or views over<br />
 again). Below is a description of MVC.</p>
<ul>
<li> <strong>Model:</strong> The model deals with the raw data and  database interaction and will contain functions<br />
 like adding records to a database or selecting specific database  records. In CI the model<br />
 component is not required and can be included in the controller.</li>
<li> <strong>View:</strong> The view deals with displaying the data and  interface controls to the user with.<br />
 In CI the view could be a web page, rss feed, ajax data or any other  â€œpageâ€.</li>
<li> <strong>Controller:</strong> The controller acts as the in between  of view and model and, as the name suggests,<br />
 it controls what is sent to the view from the model. In CI, the  controller is also the place to load libraries and helpers.</li>
</ul>
<p>An example of a MVC approach would be for a contact form.</p>
<ol>
<li> The user interacts with the view by filling in a form and  submitting it.</li>
<li> The controller receives the POST data from the form, the controller  sends this data to the model<br />
 which updates in the database.</li>
<li> The model then sends the result of the database to the controller.</li>
<li> This result is updated in the view and displayed to the user.</li>
</ol>
<p>This may sound like alot of work to do. But, trust me; when youâ€™re  working with a large application, being able to reuse models or views  saves a great deal of time.</p>
<hr />
<h2>Step 1: Downloading CodeIgniter</h2>
<p>Too start off you will need to download CodeIgniter and upload it to  your server. Point your browser<br />
 to <a title="http://www.codeigniter.com/" href="http://www.codeigniter.com/">http://www.codeigniter.com/</a> and<br />
 click the large download button. For this tutorial we are using  version 1.70.</p>
<div><img src="http://nettuts.s3.amazonaws.com/183_codeIgniter/img/download.jpg" border="0" alt="" width="260" height="60" /></div>
<hr />
<h2>Step 2: Installing and Exploring CodeIgniter</h2>
<p>Once you have downloaded CodeIgniter, all you need to do is unzip it,  and rename the â€œCodeIgniter_1.7.0â€³ folder to<br />
 either the application name or, in this case, â€œciâ€ and upload it to  your PHP and MySQL enabled server.<br />
 Now that its on your server, Iâ€™ll explain what all the folders and  files are for:</p>
<div><img src="http://nettuts.s3.amazonaws.com/183_codeIgniter/img/folders.jpg" alt="" width="175" height="374" /></div>
<ul>
<li> The <strong>system</strong> folder stores all the files which make  CI work.
<ul>
<li> The <strong>application</strong> folder is almost identical to the  contents of the <strong>system</strong> folder<br />
 this is so the user can have files that are particular to that  application, for example if a<br />
 user only wanted to load a helper in one application he would  place it in the <strong>system/application/helpers</strong> folder<br />
 instead of the <strong>system/helpers</strong> folder.</p>
<ul>
<li> The <strong>config </strong>folder stores all the config files  relevant to the application. Which<br />
 includes information on what libaries the application should  auto load and database details.</li>
<li> The <strong>controllers </strong>folder stores all the controllers  for the application.</li>
<li> The <strong>errors </strong>folder stores all the template error  pages for the application. When<br />
 an error occurs the error page is generated from one of  these templates.</li>
<li> The <strong>helpers </strong>folder stores all the helpers which  are specific to your application.</li>
<li> The <strong>hooks </strong>folder is for hooks which modify the  functioning of CIâ€™s core files,<br />
 hooks should only be used by advanced users of CI</li>
<li> The <strong>language </strong>folder stores lines of text which can  be loaded through the language<br />
 library to create multilingual sites.</li>
<li> The <strong>libraries </strong>folder stores all the libraries  which are specific to your application.</li>
<li> The <strong>models </strong>folder stores all the models for the  application.</li>
<li> The <strong>views </strong>folder stores all the views for the  application.</li>
</ul>
</li>
<li> The <strong>cache</strong> folder stores all the caches generated  by the caching library.</li>
<li> The <strong>codeigniter</strong> folder stores all the internals  which make CI work.</li>
<li> The <strong>database </strong> folder stores all the database  drivers and class which enable you to<br />
 connect to database.</li>
<li> The <strong>fonts</strong> folder stores all the fonts which can be  used by the image manipulation library.</li>
<li> The <strong>helpers</strong> folder stores all of CIâ€™s core helpers  but you can place your own helpers<br />
 in here which can be accessed by all of your applications.</li>
<li> The <strong>language </strong>folder stores all of CIâ€™s core  language files which its libaries and helpers<br />
 use. You can also put your own language folders which can  accessed by all of your applications.</li>
<li> The <strong>libaries </strong>folder stores all of CIâ€™s core  libaries but you can place your own libraries<br />
 in here which can be accessed by all of your applications</li>
<li> The <strong>logs</strong> folder stores all of the logs generated  by CI.</li>
<li> The <strong>plugin </strong>folder stores all of the plugins which  you can use. Plugins are almost identical<br />
 to helpers, plugins are functions intended to be shared by the  community.</li>
<li> The <strong>scaffolding </strong>folder stores all the files which  make the scaffolding class work.<br />
 Scaffolding provides a convenient CRUD like interface to access  information in your database<br />
 during development.</li>
</ul>
</li>
<li> The <strong>user_guide</strong> houses the user guide to CI.</li>
<li> The <strong>index.php</strong> file is the bit that does all the CI  magic it also lets the you change the<br />
 name of the <strong>system </strong>and <strong>application </strong>folders.</li>
</ul>
<hr />
<h2>Step 3: Configuring CodeIgniter</h2>
<p>Getting CI up and running is rather simple. Most of it requires you  to edit a few configuration<br />
 files.</p>
<p>You need to setup CI to point to the right base URL of the app. To do  this, open up <strong>system/application/config/config.php</strong> and<br />
 edit the base_url array item to point to your  server and CI folder.</p>
<div>
<div>
<div><a onclick="dp.sh.Toolbar.Command('ViewSource',this);return false;" href="#"></a><a onclick="dp.sh.Toolbar.Command('About',this);return false;" href="#"></a></div>
</div>
<ol>
<li>$config['base_url'] = &#8220;http://localhost/ci/&#8221;;</li>
</ol>
</div>
<pre>$config['base_url'] = "http://localhost/ci/";</pre>
<hr />
<h2>Step 4: Testing CodeIgniter</h2>
<p>Weâ€™ll do a quick test to see if CI is up and running properly. Go to http://localhost/ci/ and you<br />
 should see the following.</p>
<p><img src="http://nettuts.s3.amazonaws.com/183_codeIgniter/img/test.jpg" alt="" width="550" height="443" /></p>
<hr />
<h2>Step 5: Configuring CodeIgniter Cont.</h2>
<p>If youâ€™re up and running, we should finish the configuration. We are  starting to configure it specifically for our new helloworld app. If you  want to use a database with your application, (which in this tutorial  we do.) open up <strong>system/application/config/database.php</strong> and set the following array items to there corresponding values. This  code connects to a MySQL<br />
 database called â€œhelloworldâ€ on a localhost  with the username â€œrootâ€, and the password, â€œrootâ€.</p>
<div>
<div>
<div><a onclick="dp.sh.Toolbar.Command('ViewSource',this);return false;" href="#"></a><a onclick="dp.sh.Toolbar.Command('About',this);return false;" href="#"></a></div>
</div>
<ol>
<li>$db['default']['hostname'] = &#8220;localhost&#8221;;</li>
<li>$db['default']['username'] = &#8220;root&#8221;;</li>
<li>$db['default']['password'] = &#8220;root&#8221;;</li>
<li>$db['default']['database'] = &#8220;helloworld&#8221;;</li>
<li>$db['default']['dbdriver'] = &#8220;mysql&#8221;;</li>
</ol>
</div>
<pre>$db['default']['hostname'] = "localhost";
$db['default']['username'] = "root";
$db['default']['password'] = "root";
$db['default']['database'] = "helloworld";
$db['default']['dbdriver'] = "mysql";</pre>
<p>Additionally, since we will be using the database quite a bit, we  want it to auto load so that we donâ€™t<br />
 have to specifically load it each time we connect. Open the <strong>sys</strong><strong>tem/application/config/autoload.php </strong>file<br />
 and add â€˜databaseâ€™ to the autoload libaries array.</p>
<div>
<div>
<div><a onclick="dp.sh.Toolbar.Command('ViewSource',this);return false;" href="#"></a><a onclick="dp.sh.Toolbar.Command('About',this);return false;" href="#"></a></div>
</div>
<ol>
<li>$autoload['libraries'] = array(&#8216;database&#8217;);</li>
</ol>
</div>
<pre>$autoload['libraries'] = array('database');</pre>
<p>Currently, the CI setup will have a default controller called  â€œwelcome.phpâ€; you can find this in the <strong>system/application/controllers</strong> folder. For this tutorial, delete it and open your <strong>system/application/config/routes.php</strong> file. Change the default array item to point to the â€œhelloworldâ€  controller.</p>
<div>
<div>
<div><a onclick="dp.sh.Toolbar.Command('ViewSource',this);return false;" href="#"></a><a onclick="dp.sh.Toolbar.Command('About',this);return false;" href="#"></a></div>
</div>
<ol>
<li>$route['default_controller'] = &#8220;Helloworld&#8221;</li>
</ol>
</div>
<pre> $route['default_controller'] = "Helloworld"</pre>
<p>CI also has a view file that we do not need. Open up the <strong>system/application/view/</strong> folder<br />
 and delete the <strong>welcome_message.php</strong> file.</p>
<hr />
<h2>Step 6: Create the Helloworld Database</h2>
<p>As this isnâ€™t really a tutorial on MySQL, Iâ€™ll keep this section as  short as possible. Create a database called â€œhelloworldâ€ and<br />
 run the following SQL through phpMyAdmin (or similar MySQL client).</p>
<div>
<div>
<div>
<div><a onclick="dp.sh.Toolbar.Command('ViewSource',this);return false;" href="#"></a><a onclick="dp.sh.Toolbar.Command('About',this);return false;" href="#"></a></div>
</div>
<ol>
<li>CREATE TABLE `data` (</li>
<li> `id` int(11) NOT NULL auto_increment,</li>
<li> `title` varchar(255) NOT NULL,</li>
<li> `text` text NOT NULL,</li>
<li> PRIMARY KEY  (`id`)</li>
<li>) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;</li>
<li></li>
<li>INSERT INTO `data` (`id`, `title`, `text`) VALUES(1, &#8216;Hello World!&#8217;, &#8216;Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla</li>
<li>sapien eros, lacinia eu, consectetur vel, dignissim et, massa. Praesent suscipit nunc vitae neque. Duis a ipsum. Nunc a erat. Praesent</li>
<li>nec libero. Phasellus lobortis, velit sed pharetra imperdiet, justo ipsum facilisis arcu, in eleifend elit nulla sit amet tellus.</li>
<li>Pellentesque molestie dui lacinia nulla. Sed vitae arcu at nisl sodales ultricies. Etiam mi ligula, consequat eget, elementum sed,</li>
<li>vulputate in, augue. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae;&#8217;);</li>
</ol>
</div>
<pre>CREATE TABLE `data` (
  `id` int(11) NOT NULL auto_increment,
  `title` varchar(255) NOT NULL,
  `text` text NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;

INSERT INTO `data` (`id`, `title`, `text`) VALUES(1, 'Hello World!', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla
sapien eros, lacinia eu, consectetur vel, dignissim et, massa. Praesent suscipit nunc vitae neque. Duis a ipsum. Nunc a erat. Praesent
nec libero. Phasellus lobortis, velit sed pharetra imperdiet, justo ipsum facilisis arcu, in eleifend elit nulla sit amet tellus.
Pellentesque molestie dui lacinia nulla. Sed vitae arcu at nisl sodales ultricies. Etiam mi ligula, consequat eget, elementum sed,
vulputate in, augue. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae;');</pre>
<hr />
<h2>Step 7: Create the Helloworld Model</h2>
<p>Models are optional in CI, but itâ€™s considered best practice to use  them. They are just PHP classes that contain<br />
functions which work with information from the database. Go<br />
ahead and make a <strong>helloworld_model.php</strong> file<br />
in the <strong>system/application/models</strong> folder.<br />
In this file, create a Helloworld_model class, Helloworld_model  construct and a function called getData.</p>
<p>In the getData  function we are<br />
going to use Active Record database functions which speed up database  development times when working<br />
with CI and databases. Essentially, they are simplified functions to  create queries.</p>
<div>
<div>
<div><a onclick="dp.sh.Toolbar.Command('ViewSource',this);return false;" href="#"></a><a onclick="dp.sh.Toolbar.Command('About',this);return false;" href="#"></a></div>
</div>
<ol>
<li>&lt;?php</li>
<li>class Helloworld_model extends Model {</li>
<li></li>
<li> function Helloworld_model()</li>
<li> {</li>
<li> // Call the Model constructor</li>
<li> parent::Model();</li>
<li> }</li>
<li></li>
<li> function getData()</li>
<li> {</li>
<li> //Query the data table for every record and row</li>
<li> $query = $this-&gt;db-&gt;get(&#8216;data&#8217;);</li>
<li></li>
<li> if ($query-&gt;num_rows() &gt; 0)</li>
<li> {</li>
<li> //show_error(&#8216;Database is empty!&#8217;);</li>
<li> }else{</li>
<li> return $query-&gt;result();</li>
<li> }</li>
<li> }</li>
<li></li>
<li>}</li>
<li>?&gt;</li>
</ol>
</div>
<pre>&lt;?php
class Helloworld_model extends Model {

    function Helloworld_model()
    {
        // Call the Model constructor
        parent::Model();
    }

    function getData()
		{
			//Query the data table for every record and row
			$query = $this-&gt;db-&gt;get('data');

			if ($query-&gt;num_rows() &gt; 0)
			{
				//show_error('Database is empty!');
			}else{
				return $query-&gt;result();
			}
		}

}
?&gt;</pre>
<hr />
<h2>Step 8: Create the Helloworld Controller</h2>
<p>Letâ€™s create a controller that will display the view, and load the  model. That way, when<br />
you go to the address http://localhost/ci/index.php/helloworld/, you  will see the data from the database.<br />
In the folder <strong>system/application/controllers</strong>, create a  file called <strong>helloworld.php</strong>.<br />
In this new file, weâ€™ll create a class which has the same name as the  file.</p>
<p>Within this class, you need to create a function called â€œindexâ€. This  is the function that will be<br />
displayed when no other is provided â€“ e.g. when  http://localhost/ci/index.php/helloworld/ is<br />
visited. If, for example, we created a function called foo, we could  find this as http://localhost/ci/index.php/helloworld/foo/.</p>
<p>The key thing to remember is how CI structures its URLs; e.g  http://host/codeignitordirectory/index.php/class/function.</p>
<p>In the controller index function, we need to load the model, query  the database, and pass this queried<br />
data to the view. To load any resources into CI e.g. libraries,<br />
helpers, views, or, models, we use the load class. After we have  loaded the model, we can access it through<br />
its model name and the particular function. To pass data to a view we  need to assign it to an array<br />
item and pass the array â€“ which recreates the array items as a  variable in the view file.</p>
<div>
<div>
<div><a onclick="dp.sh.Toolbar.Command('ViewSource',this);return false;" href="#"></a><a onclick="dp.sh.Toolbar.Command('About',this);return false;" href="#"></a></div>
</div>
<ol>
<li>&lt;?php</li>
<li> class Helloworld extends Controller{</li>
<li> function index()</li>
<li> {</li>
<li> $this-&gt;load-&gt;model(&#8216;helloworld_model&#8217;);</li>
<li></li>
<li> $data['result'] = $this-&gt;helloworld_model-&gt;&lt;span class=&#8221;sql&#8221;&gt;getData&lt;/span&gt;();</li>
<li> $data['page_title'] = &#8220;CI Hello World App!&#8221;;</li>
<li></li>
<li> $this-&gt;load-&gt;view(&#8216;helloworld_view&#8217;,$data);</li>
<li> }</li>
<li> }</li>
<li>?&gt;</li>
</ol>
</div>
<pre>&lt;?php
	class Helloworld extends Controller{
		function index()
		{
			$this-&gt;load-&gt;model('helloworld_model');

			$data['result'] = $this-&gt;helloworld_model-&gt;getData();
			$data['page_title'] = "CI Hello World App!";

			$this-&gt;load-&gt;view('helloworld_view',$data);
	    }
	}
?&gt;</pre>
<p>If we visited  http://localhost/ci/index.php/helloworld/ now, it  wouldnâ€™t work; this is because the view file does not exist.</p>
<div><img src="http://nettuts.s3.amazonaws.com/183_codeIgniter/img/error.jpg" alt="" width="550" height="443" /></div>
<hr />
<h2>Step 9: Create the Helloworld View</h2>
<p>The view file is what the user sees and interacts with, it could be a  segment of a page, or the whole page. You can pass an array of  variables to the view through the second argument<br />
of the load model function. To make the view for our tutorial, create a  new file called <strong>helloworld</strong><strong>_view.php</strong> in the <strong>system/application/view</strong> folder. Next, we just  need to create our normal html, head<br />
and body elements, and then a header and paragraph for the information  from the database. To display all<br />
the records received from the database, we put it in a â€œforeachâ€ loop<br />
which loops through all the elements.</p>
<div>
<div>
<div><a onclick="dp.sh.Toolbar.Command('ViewSource',this);return false;" href="#"></a><a onclick="dp.sh.Toolbar.Command('About',this);return false;" href="#"></a></div>
</div>
<ol>
<li>&lt;html&gt;</li>
<li> &lt;head&gt;</li>
<li> &lt;title&gt;&lt;?=$page_title?&gt;&lt;/title&gt;</li>
<li> &lt;/head&gt;</li>
<li> &lt;body&gt;</li>
<li> &lt;?php foreach($result as $row):?&gt;</li>
<li> &lt;h3&gt;&lt;?=$row-&gt;title?&gt;&lt;/h3&gt;</li>
<li> &lt;p&gt;&lt;?=$row-&gt;text?&gt;&lt;/p&gt;</li>
<li> &lt;br /&gt;</li>
<li> &lt;?php endforeach;?&gt;</li>
<li> &lt;/body&gt;</li>
<li>&lt;/html&gt;</li>
</ol>
</div>
<pre>&lt;html&gt;
	&lt;head&gt;
		&lt;title&gt;&lt;?=$page_title?&gt;&lt;/title&gt;
	&lt;/head&gt;
	&lt;body&gt;
		&lt;?php foreach($result as $row):?&gt;
		&lt;h3&gt;&lt;?=$row-&gt;title?&gt;&lt;/h3&gt;
		&lt;p&gt;&lt;?=$row-&gt;text?&gt;&lt;/p&gt;
		&lt;br /&gt;
		&lt;?php endforeach;?&gt;
	&lt;/body&gt;
&lt;/html&gt;</pre>
<p>You may have noticed that we are using php alternative syntax, this  provides an convenient and time<br />
saving way to write echo statements.</p>
<hr />
<h2>Step 10: Ta-da and Some Extras</h2>
<p>When you visit â€œhttp://localhost/ci/index.php/helloworld/â€, you<br />
should see something similar to this.</p>
<div><img src="http://nettuts.s3.amazonaws.com/183_codeIgniter/img/ta-da.jpg" alt="" width="550" height="443" /></div>
<p>But we arenâ€™t done yet. There are a few things you can do to improve  your CodeIgniter experience -<br />
like removing  that annoying  index.php bit out of the URL. You  can accomplish this task by creating a .htaccess file in the root  folder, and adding the following code.</p>
<pre>RewriteEngine on
RewriteCond $1 !^(index\.php|images|robots\.txt)
RewriteRule ^(.*)$ ci/index.php/$1 [L]
</pre>
<p>Youâ€™ll also need to open up the <strong>config.php</strong> file in <strong>system/application/config/</strong> and edit the index_page array item to a blank string.</p>
<div>
<div>
<div><a onclick="dp.sh.Toolbar.Command('ViewSource',this);return false;" href="#"></a><a onclick="dp.sh.Toolbar.Command('About',this);return false;" href="#"></a></div>
</div>
<ol>
<li>$config['index_page'] = &#8220;&#8221;;</li>
</ol>
</div>
<pre>$config['index_page'] = "";</pre>
<p>Another nifty trick is to turn on CIâ€™s ability to parse PHP  alternative syntax if its<br />
not enabled by the server. To do this, open up the same  file as before, <strong>system/application/config/config.php</strong>,  and set the rewrite_short_tags array item to TRUE.</p>
<div>
<div>
<div><a onclick="dp.sh.Toolbar.Command('ViewSource',this);return false;" href="#"></a><a onclick="dp.sh.Toolbar.Command('About',this);return false;" href="#"></a></div>
</div>
<ol>
<li>$config['rewrite_short_tags'] = TRUE;</li>
</ol>
</div>
<pre>$config['rewrite_short_tags'] = TRUE;</pre>
]]></content:encoded>
			<wfw:commentRss>http://freelance-php-developer.phpmysql.co.za/2010/06/php-developer-codeigniter-mvc-framework/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>What is MVC ?</title>
		<link>http://freelance-php-developer.phpmysql.co.za/2010/06/what-is-mvc/</link>
		<comments>http://freelance-php-developer.phpmysql.co.za/2010/06/what-is-mvc/#comments</comments>
		<pubDate>Sun, 13 Jun 2010 15:55:42 +0000</pubDate>
		<dc:creator>admin</dc:creator>
		
		<guid isPermaLink="false">http://freelance-php-developer.phpmysql.co.za/?p=77</guid>
		<description><![CDATA[Model View Controller MVC MVC is a design pattern. A Design pattern is a code structure that allows for common coding frameworks to be replicated quickly. You might think of a design pattern as a skeleton or framework on which your application will be built. In the MVC framework that is created in this tutorial, [...]]]></description>
			<content:encoded><![CDATA[<p><!--content starts --></p>
<h1>Model View Controller MVC</h1>
<p>MVC is a design pattern. A Design pattern is a code structure that  allows for common coding frameworks to be replicated quickly. You might  think of a design pattern as a skeleton or framework on which your  application will be built.</p>
<p>In the MVC framework that is created in this tutorial, several key  points will be raised. The first is the frameworks needs a single point  of entry, ie: index.php. This is where all access to the site must be  controlled from. To ensure that a single point of entry is maintained,  htaccess can be utilized to ensure no other file may be accessed, and  that we hide the index.php file in the url. Thus creating SEO and user  friendly URL&#8217;s.</p>
<p>It is beyond the scope of this tutorial to show how to set up htaccess  and mod_rewrite and more information on these can be gained from the  Apache manual. The .htaccess file itself looks like this.</p>
<div>RewriteEngine on</p>
<p>RewriteCond %{REQUEST_FILENAME} !-f<br />
RewriteCond %{REQUEST_FILENAME} !-d</p>
<p>RewriteRule ^(.*)$ index.php?rt=$1 [L,QSA]</p>
</div>
<p>The .htaccess file will permit access to the site via urls such as</p>
<p>http://www.example.com/news/show</p>
<p>If you do not have mod_rewrite available, the entry to the site will be  the same, except that the URL will contain the values needed such as:</p>
<p>http://www.example.com/index.php?rt=news/show</p>
]]></content:encoded>
			<wfw:commentRss>http://freelance-php-developer.phpmysql.co.za/2010/06/what-is-mvc/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>PHP freelancer Retrieving Data in a Range by SQL BETWEEN</title>
		<link>http://freelance-php-developer.phpmysql.co.za/2010/03/php-freelancer-retrieving-data-in-a-range-by-sql-between/</link>
		<comments>http://freelance-php-developer.phpmysql.co.za/2010/03/php-freelancer-retrieving-data-in-a-range-by-sql-between/#comments</comments>
		<pubDate>Sun, 28 Mar 2010 10:12:32 +0000</pubDate>
		<dc:creator>admin</dc:creator>
		
		<guid isPermaLink="false">http://freelance-php-developer.phpmysql.co.za/?p=70</guid>
		<description><![CDATA[Working with Database Create a database with a specified name if it does not exist in database server CREATE DATABASE [IF NOT EXISTS] database_name Use database or change current database to another database you are working with USE database_name Drop a database with specified name permanently. All physical file associated with the database is no [...]]]></description>
			<content:encoded><![CDATA[<div>
<h2>Working with Database</h2>
<p>Create a database with a specified name if it does not exist  in database server</p>
<pre>CREATE DATABASE [IF NOT EXISTS] database_name</pre>
<p>Use database or change current database to another database  you are working with</p>
<pre>USE database_name</pre>
<p>Drop a database with specified name permanently. All  physical file associated with the database is no longer exists.</p>
<pre>DROP DATABASE [IF EXISTS] database_name</pre>
<p>Show all available databases in database server</p>
<pre>SHOW DATABASES</pre>
<h2>Working with Table</h2>
<p>Lists all tables in a database.</p>
<pre>SHOW TABLES</pre>
<p>Create table statement defines the structure of table in a  database.</p>
<pre> CREATE [TEMPORARY] TABLE [IF NOT EXISTS] <em>table_name</em>
 (<em>create_clause ,</em>...) [<em>table_options</em>]
 [[IGNORE|REPLACE] <em>select</em>]</pre>
<p>Altering table structure</p>
<pre>ALTER [IGNORE] TABLE <em>table_name</em> <em>actions</em></pre>
<p>Actions can be one of the following actions:</p>
<pre>ADD [COLUMN]</pre>
<p>Add a new column into a table</p>
<pre>DROP [COLUMN]</pre>
<p>Drop an existing column in a table</p>
<pre>ADD INDEX [name](column_name, ...)</pre>
<p>Add index with a specific name to a table on a column</p>
<pre>DROP INDEX index_name Drop an index from a table</pre>
<p>ADD PRIMARY KEY (column_name,&#8230;)</p>
<p>Add primary key into a tables</p>
<pre>DROP PRIMARY KEY</pre>
<p>Drop primary key from a table</p>
<p>Deleting table permanently</p>
<pre> DROP TABLE [IF EXISTS] <em>table_name</em> [, <em>name2</em>, ...]
 [RESTRICT | CASCADE]
</pre>
<p>Give information about the table or column.</p>
<pre>DESCRIBE table [column_name]
DESC table [column_name]<strong><em>
 </em></strong></pre>
<h2>Working with Index</h2>
<p>Creating an index with the specified name on a table</p>
<pre>CREATE [UNIQUE|FULLTEXT] INDEX index_name
ON table (column_name,...)</pre>
<p>Removing a specified index from table</p>
<pre>DROP INDEX index_name</pre>
<h2>Retrieving Data</h2>
<p>Retrieving complete data in a database table</p>
<pre>SELECT * FROM table_name</pre>
<p>Retrieving specified data which is shown in the column list  from a database table</p>
<pre>SELECT column_name, column_name2â€¦.
FROM table_name</pre>
<p>Retrieving unique records</p>
<pre>SELECT DISTINCT (column_name)
FROM table_name</pre>
<p>Retrieving data from multiples table using join</p>
<pre>SELECT *
FROM table_name1
INNER JOIN table_name2 ON conditions</pre>
<pre>SELECT *
FROM table_name1
LEFT JOIN table_name2 ON conditions</pre>
<p>SELECT *<br />
FROM table_name1<br />
RIGHT JOIN table_name2 ON conditions</p>
<p>Counting number of rows in a database table</p>
<pre>SELECT COUNT (*)
FROM table_name</pre>
<p>Sorting ascending or descending retrieved data based on one  or more column</p>
<pre>SELECT column_name, column_name2â€¦.
FROM table_name
ORDER BY column_name ASC [DESC], column_name2 ASC [DESC],</pre>
<p>Group the retrieved rows data</p>
<pre>SELECT *
FROM table_name
GROUP BY column_name</pre>
<h2>Matching Data based on a pattern</h2>
<p>Matching data using LIKE operator</p>
<pre>SELECT * FROM table_name
WHERE column_name LIKE â€˜%value%â€™</pre>
<h2>Matching data using regular expression</h2>
<pre>SELECT * FROM table_name
WHERE column_name RLIKE â€˜regular_expressionâ€™
<div>
<div>
<div id="contentarea">
Â 

Â 

<strong>Mark
 BSc Honours in Computer Science
 Software Architect / Developer
 Mobile 079 9111 855</strong>

<strong>Email <a href="mailto:info@mydeveloper.co.za"><strong>info@mydeveloper.co.za</strong></a></strong>
</div>
</div>
</div>
</pre>
</div>
]]></content:encoded>
			<wfw:commentRss>http://freelance-php-developer.phpmysql.co.za/2010/03/php-freelancer-retrieving-data-in-a-range-by-sql-between/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Querying data by using SQL UNION</title>
		<link>http://freelance-php-developer.phpmysql.co.za/2010/03/querying-data-by-using-sql-union/</link>
		<comments>http://freelance-php-developer.phpmysql.co.za/2010/03/querying-data-by-using-sql-union/#comments</comments>
		<pubDate>Sun, 28 Mar 2010 10:05:00 +0000</pubDate>
		<dc:creator>admin</dc:creator>
		
		<guid isPermaLink="false">http://freelance-php-developer.phpmysql.co.za/?p=68</guid>
		<description><![CDATA[SQL UNION allows you to combine two or more result sets from select statements into a single result set. The usage of using SQL UNION is as follows: SELECT statement UNION [DISTINCT &#124; ALL] SELECT statement UNION [DISTINCT &#124; ALL] â€¦ The column list of each individual SELECT statement must have the same data type. [...]]]></description>
			<content:encoded><![CDATA[<div>
<p>SQL UNION allows you to combine two or more result sets from select statements into a single result set. The usage of using SQL UNION is as follows:</p>
<pre>SELECT statement
UNION [DISTINCT | ALL]
SELECT statement
UNION [DISTINCT | ALL]</pre>
<p>â€¦<br />
The column list of each individual SELECT statement must have the same data type. By default the UNION removes all duplicated rows from the result set even if you donâ€™t explicit using DISTINCT after the UNION keyword. If you use UNION ALL explicitly, the duplicated rows will remain in the result set. Letâ€™s practice with couples of examples which use SQL UNION. Suppose you want to combine customers and employees into one, you just perform the following query:</p>
<pre>SELECT customerNumber id, contactLastname name
FROM customers
UNION
SELECT employeeNumber id,firstname name
FROM employees</pre>
<p>Here is the excerpt of the output</p>
<pre>    id  name
------  ---------------
   103  Schmitt
   112  King
   114  Ferguson
   119  Labrune
   121  Bergulfsen
   124  Nelson
   125  Piestrzeniewicz
   128  Keitel
   129  Murphy
   131  Lee
</pre>
<p>In order to use ORDER BY to sort the result you have to use it after the last SELECT statement. It would be the best to parenthesize all the SELECT statements and place ORDER BY after the last one. Suppose we use the want to sort the combination of employees and customers in the query above we can do as follows:</p>
<pre>(SELECT customerNumber id,contactLastname name
FROM customers)
UNION
(SELECT employeeNumber id,firstname name
FROM employees)
ORDER BY name,id</pre>
<p>First it orders the result set by name and then by id  What if we donâ€™t use alias for each column in the SELECT statement? MySQL uses the column names in the first SELECT statement as the label of the result therefore you can rewrite the query above as follows:</p>
<pre>(SELECT customerNumber, contactLastname
FROM customers)
UNION
(SELECT employeeNumber, firstname
FROM employees)
ORDER BY contactLastname, customerNumber</pre>
<p>or you can also use the column position in the ORDER BY clause like following query</p>
<pre>(SELECT customerNumber, contactLastname
FROM customers)
UNION
(SELECT employeeNumber,firstname
FROM employees)
ORDER BY 2, 1</pre>
</div>
<div>
<div>sql union,mysql union,sql union all,sql union distinct,sql union order by,sql union sort,mysql union order by</div>
</div>
<div></div>
<div>
<h3><a title="Website Maintenance and Support" href="http://phpmysql.co.za/00index.php#" target="_blank">Contact Details </a></h3>
<p>Mark<br />
BSc Honours in Computer Science<br />
PHP Developer<br />
Mobile 079 9111 855</p>
<p>Email <a href="mailto:info@mydeveloper.co.za"><strong>info@mydeveloper.co.za </strong></a></p>
</div>
<div><script type="text/javascript">// <![CDATA[
google_ad_client = "pub-0824680748064651";
/* 300x250, created 08/11/08 */
google_ad_slot = "1604354168";
google_ad_width = 300;
google_ad_height = 250;
// ]]&gt;</script> <script src="http://pagead2.googlesyndication.com/pagead/show_ads.js" type="text/javascript">
</script><script type="text/javascript">// <![CDATA[
google_protectAndRun("ads_core.google_render_ad", google_handleError, google_render_ad);
// ]]&gt;</script><ins><ins></ins></ins></div>
]]></content:encoded>
			<wfw:commentRss>http://freelance-php-developer.phpmysql.co.za/2010/03/querying-data-by-using-sql-union/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>MySQL Advanced Queries and Subqueries</title>
		<link>http://freelance-php-developer.phpmysql.co.za/2010/03/mysql-advanced-queries-and-subqueries/</link>
		<comments>http://freelance-php-developer.phpmysql.co.za/2010/03/mysql-advanced-queries-and-subqueries/#comments</comments>
		<pubDate>Sat, 27 Mar 2010 21:26:39 +0000</pubDate>
		<dc:creator>admin</dc:creator>
		
		<guid isPermaLink="false">http://freelance-php-developer.phpmysql.co.za/?p=65</guid>
		<description><![CDATA[In the real database programming task, you usually does not select data from just one table because of the normalization process (a big table is divided into a subset of smaller tables). So to get the complete data, you need to use SQL JOIN clause in SELECT statement. The normal form of SQL JOIN clause [...]]]></description>
			<content:encoded><![CDATA[<div>
<p>In the real database programming task, you usually does not select data from just one table because of the normalization process (a big table is divided into a subset of smaller tables). So to get the complete data, you need to use SQL JOIN clause in SELECT statement. The normal form of SQL JOIN clause in MySQL is simple follows:</p>
<pre> SELECT column_list FROM table_1
 [INNER | LEFT | RIGHT] table_2 ON conditions_2
 [INNER | LEFT | RIGHT] table_3 ON conditions_3 ...
 WHERE conditions
</pre>
<p>After SELECT keyword is a list of column name in which you want to retrieve the data. These columns have to be in the tables you select such as table_1, table_2&#8230; If the columns&#8217; name in those tables are the same, you have to explicit declare the as the form <em>table_name</em>.<em>column_name</em>, otherwise MySQL will returns you an error message to say that the column name you selected is ambiguous. Next you will list the main table and then a list of table you want to join. You can use INNER JOIN, LEFT JOIN or RIGHT JOIN. You can join a table with more than twotables or even with itself. In the JOIN clause you have to declare the join conditions. If all the conditions on each join clause match, MySQL will return the corresponding data.</p>
<h2>Using INNER JOIN</h2>
<p>INNER JOIN is used to retrieve the data from all tables listed based on condition listed after keyword ON. If the condition is not meet, nothing is returned. For example, see the followingtables in our  <em>classicmodels</em> sample database. We have <em>employees</em> table and <em>offices</em> table. Two tables are linked together by the column <em>officeCode.</em> To find out who is in which country and state we can use INNER JOIN to join these tables. Here is the SQL code:</p>
<pre>SELECT employees.firstname,
       employees.lastname,
       offices.country,
       offices.state
FROM employees
INNER JOIN offices
  ON offices.officeCode = employees.officeCode
</pre>
<p>And we will get the data like this:</p>
<pre>+-----------+-----------+-----------+------------+
| firstname | lastname  | country   | state      |
+-----------+-----------+-----------+------------+
| Diane     | Murphy    | USA       | CA         |
| Mary      | Patterson | USA       | CA         |
| Jeff      | Firrelli  | USA       | CA         |
| William   | Patterson | Australia | NULL       |
| Gerard    | Bondur    | France    | NULL       |
| Anthony   | Bow       | USA       | CA         |
| Leslie    | Jennings  | USA       | CA         |
| Leslie    | Thompson  | USA       | CA         |
| Julie     | Firrelli  | USA       | MA         |
| Steve     | Patterson | USA       | MA         |
| Foon Yue  | Tseng     | USA       | NY         |
| George    | Vanauf    | USA       | NY         |
| Loui      | Bondur    | France    | NULL       |
| Gerard    | Hernandez | France    | NULL       |
| Pamela    | Castillo  | France    | NULL       |
| Larry     | Bott      | UK        | NULL       |
| Barry     | Jones     | UK        | NULL       |
| Andy      | Fixter    | Australia | NULL       |
| Peter     | Marsh     | Australia | NULL       |
| Tom       | King      | Australia | NULL       |
| Mami      | Nishi     | Japan     | Chiyoda-Ku |
| Yoshimi   | Kato      | Japan     | Chiyoda-Ku |
| Martin    | Gerard    | France    | NULL       |
+-----------+-----------+-----------+------------+
23 rows in set (0.02 sec)
</pre>
<p>If you want to find only employees in USA, just execute this query:</p>
<pre>SELECT e.firstname,
       e.lastname,
       state
FROM employees e
INNER JOIN offices p
  ON o.officeCode = e.officeCode AND country = 'USA'</pre>
<p>Here is the data back</p>
<pre>+-----------+-----------+-------+
| firstname | lastname  | state |
+-----------+-----------+-------+
| Diane     | Murphy    | CA    |
| Mary      | Patterson | CA    |
| Jeff      | Firrelli  | CA    |
| Anthony   | Bow       | CA    |
| Leslie    | Jennings  | CA    |
| Leslie    | Thompson  | CA    |
| Julie     | Firrelli  | MA    |
| Steve     | Patterson | MA    |
| Foon Yue  | Tseng     | NY    |
| George    | Vanauf    | NY    |
+-----------+-----------+-------+
10 rows in set (0.00 sec)</pre>
<h2>Using LEFT and RIGHT JOIN</h2>
<p>LEFT JOIN can be used when you want to retrieve the data from the main table (table1) even if there is no match in other tables (table_2, table_3&#8230;.). While RIGHT JOIN is used to retrieve the data the from all other tables (table_2, table_3&#8230;) even if there is no match in the main table. As an example, in our classicalmodels sample database, when the company want to establish a new office, the SQL script to insert a new office to the databse as follows:</p>
<pre>INSERT INTO classicmodels.offices
	(officeCode,
         city,
         phone,
         addressLine1,
         addressLine2,
	 state,
	 country,
	 postalCode,
	 territory
	)
VALUES  ('8',
        'Boston',
        '+1 215 837 0825',
        '1550 dummy street',
         'dummy address',
	'MA',
	'USA',
	'02107',
	'NA'
	)</pre>
<p>At this time, the company hasn&#8217;t any hire new employee yet so the new office does not have any employee. If we want to know employee who belongs to which office and all the offices of the company, we can use RIGHT JOIN as follows:</p>
<pre> SELECT firstname,
        lastname,
 addressLine1
 FROM employees e
 RIGHT JOIN offices o ON o.officeCode = e.officeCode</pre>
<pre>+-----------+-----------+--------------------------+
| firstname | lastname  | addressLine1             |
+-----------+-----------+--------------------------+
| Mary      | Patterson | 100 Market Street        |
| Diane     | Murphy    | 100 Market Street        |
| Jeff      | Firrelli  | 100 Market Street        |
| Anthony   | Bow       | 100 Market Street        |
| Leslie    | Jennings  | 100 Market Street        |
| Leslie    | Thompson  | 100 Market Street        |
| Julie     | Firrelli  | 1550 Court Place         |
| Steve     | Patterson | 1550 Court Place         |
| Foon Yue  | Tseng     | 523 East 53rd Street     |
| George    | Vanauf    | 523 East 53rd Street     |
| Gerard    | Bondur    | 43 Rue Jouffroy D'abbans |
| Loui      | Bondur    | 43 Rue Jouffroy D'abbans |
| Gerard    | Hernandez | 43 Rue Jouffroy D'abbans |
| Pamela    | Castillo  | 43 Rue Jouffroy D'abbans |
| Martin    | Gerard    | 43 Rue Jouffroy D'abbans |
| Mami      | Nishi     | 4-1 Kioicho              |
| Yoshimi   | Kato      | 4-1 Kioicho              |
| William   | Patterson | 5-11 Wentworth Avenue    |
| Andy      | Fixter    | 5-11 Wentworth Avenue    |
| Peter     | Marsh     | 5-11 Wentworth Avenue    |
| Tom       | King      | 5-11 Wentworth Avenue    |
| Larry     | Bott      | 25 Old Broad Street      |
| Barry     | Jones     | 25 Old Broad Street      |
| NULL      | NULL      | 1550 dummy street        |
+-----------+-----------+--------------------------+
24 rows in set (0.00 sec)</pre>
<p>As you can see, the RIGHT JOIN get the all the data from second table (offices) and data from the first table even the conditiondoes not match.</p>
<h2>Joining a Table to Itself or Self joins</h2>
<p>You can also using JOIN clause to join table to itself. Consider the following situation to our sample databse, we want to know who has to report to whom in organization structure. Here is the SQL script:</p>
<pre>SELECT concat(e.firstname,',',e.lastname) AS employee,
       concat(m.firstname,',',m.lastname) AS manager
FROM employees AS m
INNER JOIN employees AS e ON m.employeeNumber  = e.reportsTo
ORDER BY employee</pre>
<pre>+------------------+-------------------+
| employee         | manager           |
+------------------+-------------------+
| Andy,Fixter      | William,Patterson |
| Barry,Jones      | Gerard,Bondur     |
| Foon Yue,Tseng   | Anthony,Bow       |
| George,Vanauf    | Anthony,Bow       |
| Gerard,Hernandez | Gerard,Bondur     |
| Jeff,Firrelli    | Diane,Murphy      |
| Julie,Firrelli   | Anthony,Bow       |
| Larry,Bott       | Gerard,Bondur     |
| Leslie,Jennings  | Anthony,Bow       |
| Leslie,Thompson  | Anthony,Bow       |
| Loui,Bondur      | Gerard,Bondur     |
| Martin,Gerard    | Gerard,Bondur     |
| Mary,Patterson   | Diane,Murphy      |
| Pamela,Castillo  | Gerard,Bondur     |
| Peter,Marsh      | William,Patterson |
| Steve,Patterson  | Anthony,Bow       |
| Tom,King         | William,Patterson |
| Yoshimi,Kato     | Mami,Nishi        |
+------------------+-------------------+
</pre>
</div>
]]></content:encoded>
			<wfw:commentRss>http://freelance-php-developer.phpmysql.co.za/2010/03/mysql-advanced-queries-and-subqueries/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

