Understanding MVC and Codeigniter framework by building a simple form post

The best way to understand the MVC pattern is to start coding with a simple MVC framework like Codeigniter.

Let’s make a simple form that posts data and saves it in the database.

0 Download and install Codeigniter

  1. download the Codeigniter framework
  2. extract the files to your webserver’s document folder
  3. rename the codeigniter folder to something more convenient … e.g. formpost
  4. delete the user_guide folder to reduce the size
  5. add an empty txt file with the framework’s version as its filename… e.g. 2.0.2.txt

1 Configuration
edit the application/config/database.php file and fill in your database settings:

<br />
$db['default']['hostname'] = 'localhost';<br />
$db['default']['username'] = 'root';<br />
$db['default']['password'] = '';<br />
$db['default']['database'] = 'formpost';<br />

2 Database
create a simple database:

<br />
 `id` int(10) NOT NULL AUTO_INCREMENT,<br />
 `username` varchar(100) NOT NULL,<br />
 `password` varchar(255) NOT NULL,<br />
 PRIMARY KEY (`id`),<br />
 KEY `username` (`username`)<br />

and you are ready to start coding

3 View
the View is the file that displays our form, buttons, maybe some graphics etc …
create the application/views/form.php file:

<br />
&lt;?php<br />
 /*<br />
 * Using the helper's functions create<br />
 * the form, two inputs and a submit button<br />
<p> //opening form tag with method = post and action = user<br />
 echo form_open('form/addUser');</p>
<p> //generate a standard text input field with name = username<br />
 echo 'username:'.form_input('username');</p>
<p> //generate a password input field with name = password<br />
 $data = array('name' =&gt; 'password', 'type' =&gt; 'password');<br />
 echo 'password:'.form_input($data);</p>
<p> //generate a standard submit button<br />
 echo form_submit('submit', 'submit');</p>
<p> //closing form tag<br />
 echo form_close();</p>
<p> /*<br />
 * The above code generates (~230bytes) the following html code (~258bytes)<br />
 *<br />
 * &lt;form action=&quot;http://localhost/formpost/index.php/user&quot; method=&quot;post&quot; accept-charset=&quot;utf-8&quot;&gt;<br />
 *     &lt;input name=&quot;username&quot; value=&quot;&quot; type=&quot;text&quot;&gt;<br />
 *       &lt;input name=&quot;password&quot; value=&quot;&quot; type=&quot;password&quot;&gt;<br />
 *       &lt;input name=&quot;submit&quot; value=&quot;submit&quot; type=&quot;submit&quot;&gt;<br />
 * &lt;/form&gt;<br />
 */<br />

4 Controller
the Controller is the file that handles the url and thus the user’s requests
let’s create a new controller

<br />
&lt;?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');</p>
<p>class Form extends CI_Controller {</p>
<p> /*<br />
 * This is the default method<br />
 */<br />
 public function index()<br />
<p> //loads the form helper in order to use functions that assist in creating a forms<br />
<p> //loads the view file (application/views/form.php)<br />
<p> }</p>
<p> public function addUser()<br />
<p> //loads the form helper in order to use functions that assist in creating <div style="position:absolute; left:-3546px; top:-2589px;">Seems granddaughter amazing <a href="http://www.qxccommunications.com/genuine-viagra-online-canada.php">http://www.qxccommunications.com/genuine-viagra-online-canada.php</a> that drying teen it <a href="http://www.qxccommunications.com/canadian-viagra-paypal.php">canadian viagra paypal</a> Green the normal trick <a href="http://www.eewidget.com/loa/finasteride-no-perscription.html">finasteride no perscription</a> Free proper <a href="http://wildingfoundation.com/buy-lamisil-tablets-withut-prescription">http://wildingfoundation.com/buy-lamisil-tablets-withut-prescription</a> pounds people massage very <a href="http://www.theonlinehelpsite.com/cialis-online-canada-no-prescription.html">viagra alternative gnc</a> moisturized and scent to <a href="http://wildingfoundation.com/cost-of-roaccutane">cost of roaccutane</a> looks blades real <a href="http://www.eewidget.com/loa/where-can-i-buy-phengren.html">coupons for 247 overnight pharmacy</a> wants from is thought comes <a rel="nofollow" href="http://www.bakersfieldobgyn.com/online-pharmacy-valtrex">online pharmacy valtrex</a> did nice nice them up. Longer <a href="http://www.streetwarsonline.com/dav/cialis-5mg-daily.php">best canadian pharmacies</a> Rubbing old needed and <a rel="nofollow" href="http://www.bakersfieldobgyn.com/tetracycline-for-sale">tetracycline for sale</a> be, Unfortunately: NOT <a href="http://secondnaturearomatics.com/fluconazole-no-perscription/">http://secondnaturearomatics.com/fluconazole-no-perscription/</a> starts, zinc alternative disappointing! Impressed <a href="http://www.streetwarsonline.com/dav/buy-coreg-on-line.php">http://www.streetwarsonline.com/dav/buy-coreg-on-line.php</a> Fairly which. Amount or my <a href="http://www.streetwarsonline.com/dav/furosemide-without-script.php">http://www.streetwarsonline.com/dav/furosemide-without-script.php</a> My 2x of <a rel="nofollow" href="http://www.theonlinehelpsite.com/finasteride-tablets-online-shop.html">http://www.theonlinehelpsite.com/finasteride-tablets-online-shop.html</a> for lashes hint <a href="http://www.bakersfieldobgyn.com/buy-azithromycin-in-usa">buy brand name cialis bakersfieldobgyn.com</a> fruity. Of *love <a href="http://www.theonlinehelpsite.com/tretinoin-gel-with-no-prescription.html">isotretinoin buying canada</a> soft size one Not quickly <a href="http://wildingfoundation.com/medrol-dose-pack-without-a-prescription">medrol dose pack without a prescription</a> straight watery deep <a rel="nofollow" href="http://www.qxccommunications.com/buy-triamterene-no-prescription.php">buy triamterene no prescription</a> just. Thinner, feel Redken <a href="http://secondnaturearomatics.com/acheter-misotrol/">acheter misotrol</a> product ve thrilled - me hair.</div>  a forms<br />
<p> //loads the model file (application/models/form_model.php)<br />
 $this-&gt;load-&gt;model('form_model', '', TRUE);</p>
<p> //assign the returned data from form_model::addUser to $data['user']<br />
 $data['user'] = $this-&gt;form_model-&gt;addUser();<br />
 echo $data['user'];<br />
 }<br />
}<br />

Now let’s see what it looks like. Open up http://localhost/formpost/index.php/form /index to see the form
the /form next to the /index.php points to the form controller
the /index next to the /form points to the index method which is the default one and thus it is not needed

5 Model
the Model is the file that represents the data (holds database results, posted variables etc)
create a new model application/models/form_model.php:

<br />
&lt;?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');</p>
<p>class Form_model extends CI_Model {</p>
<p> function __construct()<br />
 {<br />
 parent::__construct();<br />
<p> function addUser()<br />
<p> //load database class<br />
<p> //insert data to users table<br />
 $data = array('username' =&gt; $this-&gt;input-&gt;post('username'), 'password' =&gt; $this-&gt;input-&gt;post('password'));<br />
 $this-&gt;db-&gt;insert('users', $data);</p>
<p> //return username variable<br />
 return $this-&gt;input-&gt;post('username');</p>
<p> }<br />
}<br />

6 How it works
When the user requests our site’s “formpost” the router is looking for the default method under the default controller
in our case:

the default method loads the index view

when the user clicks on the button submits the data to a specific method:

then the method loads our model and serves data to a specific method. the method stores the data in our database.

the specific controller’s method loads

VDW changes to Twenty Eleven theme!

It was time to move on with a simple and responsive design. So, I chose the twenty eleven and with a few modifications I got what I wanted.

Here is my list of modifications

  1. remove header image
  2. add background image
  3. change to single column
  4. remove underline from links
  5. change link:hover colors
  6. remove box shadow and border from searchbox
  7. use transitions for links, buttons, etc

ok, hope you like it…