Introduction to Code Igniter: Part 3

4 comments | Posted: 27 October 06 in Tutorials, by Yannick Lyn Fatt

Please note the following tutorial was done using an older version of CodeIgniter. As such, somethings may not work properly in more recent versions of the framework. Please visit the CodeIgniter website and download version 1.3.3 or 1.4.1, if you would like to run this tutorial in it’s original form. For Updated code please download intro-to-codeigniter-code.zip


Previous tutorial code: regform-part2.zip

In Parts 1 and 2 of this Introduction to Code Igniter, I went through a few of the basics and also touched on the E-mail and Validation classes that are included with the framework. I would like to continue by giving you a glimpse of the Database class and how easy it is to insert and select data from a database using CI. Before we begin though we have a little updating to do.

Updating CI

Since the last tutorial there have been two updates to CI. There was a giant leap from version 1.3.3 to 1.4.0 and then another update to version 1.4.1. Quite a number of features were added and bugs fixed. While none of the new features/bug fixes affect this tutorial (well at least not to my knowledge), I have updated to version 1.4.1 and encourage you to do the same. For more information on what was changed, view the changelog and for instructions on updating, view the Upgrading from a Previous Version document.

Setting up CI to work with your Database

Since this tutorial will be connecting to, inserting and retrieving information from a database, we will need to setup our database. I have created a .sql file that you can use (It is included in the downloadable code for this tutorial) or you can create it yourself.

 
CREATE DATABASE `regform`;
USE `regform`;
CREATE TABLE `participants` (
`id` INT(3) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`fname` VARCHAR(255) NOT NULL ,
`email` VARCHAR(255) NOT NULL ,
`comments` TEXT NOT NULL ,
`seminar_1` VARCHAR(255) NOT NULL ,
`seminar_2` VARCHAR(255) NOT NULL ,
`seminar_3` VARCHAR(255) NOT NULL ,
`seminar_4` VARCHAR(255) NOT NULL
) ENGINE = innodb;
 
 

With our database and table created, we now need to give CI permission to connect to the database. In the application folder and in the config sub-folder, open the file called database.php and fill in the necessary information. A sample can be found below:

 
$db['default']['hostname'] = "localhost";
$db['default']['username'] = "testuser";
$db['default']['password'] = "testuser123";
$db['default']['database'] = "regform";
$db['default']['dbdriver'] = "mysql";
$db['default']['dbprefix'] = "";
$db['default']['active_r'] = TRUE;
$db['default']['pconnect'] = FALSE;
$db['default']['db_debug'] = TRUE;
 
 

Models

As I mentioned in Part 1 of the tutorial, Models generally contain database functions such as inserting, deleting, updating and retrieving information from your database. It is part of the trio that is the Model-View-Controller approach to application development.

With CI it isn’t absolutely a must to create models. In fact you can put your database queries right in your controllers, however, I would like to keep in the true spirit of MVC and keep them separated.

We will now create a model for application. Fire up your favourite text editor and insert the following:

 
<?php
class Form_model extends Model
{
  function Form_model()
  {
    parent::Model();
  }

  function add_participant()
  {
    $fname = $this->input->post(‘fname’);
    $email = $this->input->post(‘email’);
    $comments = $this->input->post(‘comments’);
    $seminars = array_pad($this->input->post(‘seminar’), 4, “not chosen”);
    $seminar_1 = $seminars[0 ];
    $seminar_2 = $seminars[1 ];
    $seminar_3 = $seminars[2 ];
    $seminar_4 = $seminars[3 ];		
    $this->db->query(“INSERT INTO participants (id, fname, email, comments, seminar_1, seminar_2, seminar_3, seminar_4) VALUES”);
  }

  function list_participants()
  {
    $query = $this->db->query(“SELECT * FROM participants”);
    return $query;
  }
}
?>
 
 

strong>Note: Take out the space between the index of the $seminars array and the closing square bracket.

Now save the file as form_model.php in the models directory of your application folder.

As you can see I have three methods (functions) in my form model. The first is simply a constructor, similar to what you have used when we created our controller in the previous tutorials. The second method is what we will use to insert the form data into our database. I called it add_participant() since that is exactly what we are doing, adding someone who would like to participate (take part) in one or more seminars. The third and final function, list_participants() is what we will use to list our participants and this we will take a look at a little later.

Everything there should be pretty straightforward except for the array_pad() function. Since the checkboxes that are selected are stored as an array and the size of the array can vary between 0-4, I wanted to store each item of the array in it’s own column in the database. But what happens when I call index 3 of the array and the array only has 2 items? I will get an error, so I used the array_pad() function to ensure that if the array has less than 4 elements it will pad/fill the empty spaces with “not chosen” and assign those to variables to be put into the database. Now I know you might be saying, “But surely there are better ways to do that?” I agree with you, there are other ways, but this is the method I chose for this example. Don’t let me spoil your fun though, feel free to use your method of choice.

Using your Models

Okay, now that we have created our model, the question you may ask is “How do I use it?” The answer to that is what I will touch on now.

We are going to load our model in our controller so open form.php in the controllers folder and add the following after $this->email->send(); in the index() method:

 
$this->load->model('Form_model','', TRUE);
$this->Form_model->add_participant();
 
 

The first line loads our model called Form_model (which is the first parameter). The second parameter allows you to assign a different object name for your model. The third parameter, when set to TRUE lets the model auto connect to the database.

The second line calls the add_participant() method that we created in our model and runs the actions we specified in that method.

That’s it! Now go to the form (http://localhost/regform/), fill it out and providing you got your success page (that we created in the previous tutorials) you can check your database and see what was submitted. Feel free to populate your database with a few more entries.

Retrieving information from a Database

Of course this tutorial wouldn’t be complete without us retrieving some information from the database and displaying it. So let’s get to it, it’s quite simple.

You might remember the third function in the Form Model called list_participant(). This is what we will use to retrieve our data from the database.

 
  function list_participants()
  {
    $query = $this->db->query("SELECT * FROM participants");
    return $query;
  }
 
 

No magic here, just a simple SELECT query is all it takes and the result will be returned to whatever calls it.

Now open form.php again from in the controllers folder and lets create another method called results(). It will look a little something like this:

 
  function results()
  {
    $this->load->model('Form_model', '', TRUE);
    $data['query'] = $this->Form_model->list_participants();
    $this->load->view('results', $data);
  }
 
 

With that complete, let’s create our view where the results will be displayed. strong>Note: Only the table is shown.

 
<h1>Participants</h1>
<p>Here is our wonderful list of participants:</p>
<table>
	<tr>
		<th>ID</th>
		<th>Name</th>
		<th>E-mail Address</th>
		<th>Seminar 1</th>
		<th>Seminar 2</th>
		<th>Seminar 3</th>
		<th>Seminar 4</th>
		<th>Comments</th>
	</tr>
<?php
if($query->num_rows() > 0):
   foreach ($query->result() as $row):
?>	
	<tr>
		<td><?php echo $row->id; ?></td>
		<td><?php echo $row->fname; ?></td>
		<td><?php echo $row->email; ?></td>
		<td><?php echo $row->seminar_1; ?></td>
		<td><?php echo $row->seminar_2; ?></td>
		<td><?php echo $row->seminar_3; ?></td>
		<td><?php echo $row->seminar_4; ?></td>
		<td><?php echo $row->comments; ?></td>
	</tr>
<?php
	endforeach;
endif;
?>
</table>
 
 

This is all pretty standard stuff for any PHP programmer. I created the table that my results will be displayed in and around one row I essentially created a loop. So for each result, I assign it the name $row and each row has various columns that I refer to like so, $row->id, where id corresponds to the actual id column in the database and so on for the other columns. The if($query->num_rows() > 0): line, simply says that as long as there are more than 0 rows returned, then display a table row for each one, otherwise don’t create any table rows.

Summary

And there you have it, just like that we have created a mini application that taught you some of the basics of Code Igniter, gave you a brief overview of the E-mail and Validation classes and also a look into CI’s Database class and how to use Models. Also while I didn’t go through it in this tutorial, CI does have a modified version of the Active Record Database Pattern that allows information to be retrieved, inserted, and updated in your database with minimal scripting. More information on CI’s implementation can be found in the documention.

I do hope you found these introductory tutorials helpful. If you are looking for a good and lightweight PHP Framework, then do give CI a try and if you need help or more information head on over to the CI Forums.

Peace and God Bless.

Finished tutorial code: regform-part3.zip

Discuss This Topic

  1. 1 Pozycjonowanie

    Yannick Lyn Fatt thanks for Introduction to Code Igniter: Part 3. Keep up the good work. Greetings from Poland

     
  2. 2 Derek Allard

    Well written tutorial! In CI 1.5 (currently in release candidate), a table class has been introduced that would make generating the table above even easier!

    $this->table->set_heading(‘Name’, ‘Email’);
    // you’d probably use a foreach here for each db result
    $this->table->add_row($array);
    return $this->table->generate();

    Derek

     
  3. 3 Yannick

    Pozycjonowanie: Thanks I appreciate it. Nice site by the way.

    Derek: Yeah I saw that and am really looking forward to that, I had wanted to hold out a bit more till 1.5 before doing this tutorial, but decided to just go ahead. Perhaps once it’s out I’ll do some more tutorials.

    You’ve done some amazing work with CI and I enjoyed your video tutorial too showing your simple CI application with AJAX. And how could I forget Bamboo Invoice which has helped me to learn more about using CI. Keep up the good work.

     
  4. 4 Derek Allard

    Thanks man, appreciate that!

    CI 1.5 is out formally now. Perhaps time for another video tutorial ;)

     

Comments closed after 2 weeks.