Modeling Data With CodeIgniter

This is going to be the last chapter in my series on CodeIgniter before we begin our project. It’s important to understand how to model data for consumption by views.

Getting Started with CodeIgniterI’m not going to go into the basics of MySQL here. There are plenty of courses out there to learn about that. For a lot of what you do in CodeIgniter, you’re not going to be writing SQL, anyway.

We’ll be using CI’s ActiveRecord. Please note this is not Ruby’s ActiveRecord, but CI’s implementation of the active record pattern. In Ruby on Rails, ActiveRecord is the implementation of the same pattern, so don’t be confused by the name. Laravel also implements active record, using the name Eloquent. From what I’ve heard, CI is going to be changing the name of its ActiveRecord to Query Builder in CI 3.0.

See All of Scott’s CodeIgniter Stories.

I’ll assume you’ve been able to connect to your database. If you haven’t, review this post. You’ll know if you haven’t — simply refreshing a page in CI will throw an error if there’s a database connection problem. If you don’t get an error, then you’re connected.

That said, we’re ready to start writing our first model. CI takes a different approach than Ruby on Rails, or even Laravel, which is modeled on RoR. In both of those, one model represents one table. So if you have a “users” table in your database, you have a User model. In RoR and Laravel, the model’s name is always the singular of the table name.  Models in RoR and Laravel also instantly give you access to all of the table columns as properties.

CodeIgniter works completely differently. In CI, models can represent most anything. They’re completely flexible. Initially this freedom seemed like a plus to me, but the more I’ve worked with Ruby on Rails and Laravel, the less I’ve liked it. For the purposes of this tutorial, I’m going to work on the one-table, one-model premise. However, that doesn’t give me all of the columns in the table as properties.

Let’s start with the basics. Every model follows this pattern:

<!--?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');-->

class Model_name extends CI_Model {


Inside your controllers, you simply call the “load” method on the model to gain access to it, like this:

$myVariable = $this->model_name->function_name();

Note the class name is capitalized, like any class, but the model name in the above call is lower-cased. This is a CI convention. The model name becomes the class name in the second line, and then you can call a function off that.

You can also pass the data to your view by assigning it to “$data[‘myVariable’]”.  In the view, you can then loop through the data in a “foreach” or “for” loop.

That brings us back to CI’s ActiveRecord. You can read the API in a link below. Ellis Labs explains the API in great detail, and there are a lot of terrific, helpful examples.

A model is made up of individual functions. If you’re building a large application, you’re going to have lots of functions in your model. You must organize them well since CI doesn’t enforce any structure. An example of a function in a model is:

public function myFirstFunction($var1, $var2) {
$this->db->where('var1', $var1);
$this->db->where('var2', $var2);

Because these calls are chainable as of PHP 5.x, you can also write:

$this->db->select('*')->where('var1', $var1)->where('var2, $var2)->get('users')->result();

By the way, “select(‘*’)” is the default, so if you’re not selecting columns, you can leave out “db->select(‘*’)”. In raw SQL, this query is the same as:

'SELECT * FROM users WHERE var1 =' .  $var1 . ' AND var2=' . $var2;

By the way, don’t use SQL in the above manner, because you’ll risk SQL injection. It’s just an example. But CodeIgniter safely escapes all of your queries, so you don’t have to worry about that.

This call also does one additional thing: It creates an object of your data with properties for each column. That’s what “result()” does. If you want an array instead, you can use “result_array()”.

After passing the data to the view with $data(‘users’), you can loop through your data like this if you’re building an unordered list:

<!--?php foreach ($users as $user) : ?>-->

  • <!–?php echo $user->username; ?>–>

<!–?php endforeach; ?>–>

Substitute your variable and property names above, based on the data you’re working with.

This example assumes you’re working with a “result()” object. Test out your view to see if you’ve gotten the expected results. Assuming you’re working with a data table that contains a list of users and the column name is “username” in the “users” table, you should have a list of all of your users in an unordered list.

Although in practice I’ve almost never had to write any raw SQL, CI will let you do so when it’s necessary. The API is pretty extensive and covers all of SQL grammar’s most common parts. It’s not as powerful as the ActiveRecord you get in RoR or Laravel, but I’ve always found it gets the job done reliably. If this isn’t clear yet, it should become more so when we dive into building our first CI app, beginning in my next installment.

Related Links

One Response to “Modeling Data With CodeIgniter”