Skip to main content

CodeIgniter: Getting Started With a Simple Example

CodeIgniter: Getting Started With a Simple Example

Introduction


CodeIgniter is a powerful PHP framework that can help you greatly speed up the development of your web applications. It is has a small performance footprint due to the modular approach to loading its libraries and does a great job separating logic from presentation by using a Model-View-Controller (MVC) dynamic.

In this tutorial, you will learn how to create a very simple application that displays content from the database. It is not meant to provide the solution to building your own CMS, but rather to illustrate how CodeIgniter can be used. Additionally, it seeks to put in practice some of the lessons learned in the previous article and assumes you already have CodeIgniter installed on your development environment and have configured it as described in the first tutorial.

The Plan


In this article, you will see how to use some of CodeIgniter’s classes and functions to query a database table containing news items and displaying them individually on the page. For this we will create a Controller, a Model and a View, as well as the database to hold the information (although the latter part will also be assumed since there are many resources available where you can brush up on your MySQL skills).

The database requirements are as follows: a table called news which contains 3 columns: id (primary and auto incremented), title, and body. Of course you can add more, but this is enough for the example. And then create a couple of rows in the table with some dummy news items. You can use this great tutorial to help you create your database if you don’t know how. Additionally, make sure that you configured CodeIgniter to use this database.

The Model


Now that we have the database properly set up and CodeIgniter is aware of it, it’s time to create a Model class that will query it for information. Navigate to the application/models folder of your CodeIgniter installation and create a new php file called news_model.php (You can name the file whatever you want). Add a php opening tag to the top of the file and create the Model class by extending the default CI one (remember that class names begin with capital letters):
class News_model extends CI_Model {

}

Inside this class, you have to then create a function (called a method) to query the database. CodeIgniter uses the Active Record pattern that makes working with the database very easy. All you have to do is load the database class in the constructor function (if you have not autoloaded it already in the autoload.php file under the application/config folder) and you are good to go. To load it, paste the following function into the class:
public function __construct() {
  $this->load->database(); 
}

This will make it that all methods within this class will be able to make use of the database functions. Next, you need the above mentioned method in the Model class to read the information from your database table:
public function get_news($id) {
  if($id != FALSE) {
    $query = $this->db->get_where('news', array('id' => $id));
    return $query->row_array();
  }
  else {
    return FALSE;
  }
}

It simply checks that an ID is passed to it before retrieving from the news table the row with the ID passed and returning it as an associative array containing all the columns in the table. If no ID is passed, the function will return FALSE.

So that takes care of retrieving the information. Now it’s time to handle the request from the client that demands this information. Save the file and exit.

The Controller


Navigate to the application/controllers folder and create a new php file called news.php (The name of this file must correspond to the name of the class you are about to give). Within the file, start again by opening the php tag and creating the Controller class by extension:
class News extends CI_Controller {

}

Now it’s time to work inside this class to handle the requests and display the relevant piece of news. All the heavy lifting happens in the Model class so all we have to do here is load it and pass it to the ID argument of the piece of news we want displayed. So let’s create a function called show() that will handle this:
public function show($id) {
    $this->load->model('news_model');
    $news = $this->news_model->get_news($id);
    $data['title'] = $news['title'];
    $data['body'] = $news['body'];
    $this->load->view('news_article', $data);

Introduction


CodeIgniter is a powerful PHP framework that can help you greatly speed up the development of your web applications. It is has a small performance footprint due to the modular approach to loading its libraries and does a great job separating logic from presentation by using a Model-View-Controller (MVC) dynamic.

In this tutorial, you will learn how to create a very simple application that displays content from the database. It is not meant to provide the solution to building your own CMS, but rather to illustrate how CodeIgniter can be used. Additionally, it seeks to put in practice some of the lessons learned in the previous article and assumes you already have CodeIgniter installed on your development environment and have configured it as described in the first tutorial.

The Plan


In this article, you will see how to use some of CodeIgniter’s classes and functions to query a database table containing news items and displaying them individually on the page. For this we will create a Controller, a Model and a View, as well as the database to hold the information (although the latter part will also be assumed since there are many resources available where you can brush up on your MySQL skills).

The database requirements are as follows: a table called news which contains 3 columns: id (primary and auto incremented), title, and body. Of course you can add more, but this is enough for the example. And then create a couple of rows in the table with some dummy news items. You can use this great tutorial to help you create your database if you don’t know how. Additionally, make sure that you configured CodeIgniter to use this database.

The Model


Now that we have the database properly set up and CodeIgniter is aware of it, it’s time to create a Model class that will query it for information. Navigate to the application/models folder of your CodeIgniter installation and create a new php file called news_model.php (You can name the file whatever you want). Add a php opening tag to the top of the file and create the Model class by extending the default CI one (remember that class names begin with capital letters): class News_model extends CI_Model { }
Inside this class, you have to then create a function (called a method) to query the database. CodeIgniter uses the Active Record pattern that makes working with the database very easy. All you have to do is load the database class in the constructor function (if you have not autoloaded it already in the autoload.php file under the application/config folder) and you are good to go. To load it, paste the following function into the class: public function __construct() { $this->load->database(); }
This will make it that all methods within this class will be able to make use of the database functions. Next, you need the above mentioned method in the Model class to read the information from your database table: public function get_news($id) { if($id != FALSE) { $query = $this->db->get_where('news', array('id' => $id)); return $query->row_array(); } else { return FALSE; } }
It simply checks that an ID is passed to it before retrieving from the news table the row with the ID passed and returning it as an associative array containing all the columns in the table. If no ID is passed, the function will return FALSE.

So that takes care of retrieving the information. Now it’s time to handle the request from the client that demands this information. Save the file and exit.

The Controller


Navigate to the application/controllers folder and create a new php file called news.php (The name of this file must correspond to the name of the class you are about to give). Within the file, start again by opening the php tag and creating the Controller class by extension: class News extends CI_Controller { }
Now it’s time to work inside this class to handle the requests and display the relevant piece of news. All the heavy lifting happens in the Model class so all we have to do here is load it and pass it to the ID argument of the piece of news we want displayed. So let’s create a function called show() that will handle this: public function show($id) { $this->load->model('news_model'); $news = $this->news_model->get_news($id); $data['title'] = $news['title']; $data['body'] = $news['body']; $this->load->view('news_article', $data); }
What this method does is the following: the first line loads the news_model we just created. The second one uses it and stores the query result (which is an associative array containing all the columns in the row) in the $news variable. The third and fourth lines store in the $data array the title and body of the retrieved news and the fifth one loads the View we want to use to display them and passes the information along. Each key in the $data array will represent a variable to be printed out in the View file. So let’s see how we build that.

The View


Navigate to the application/views folder and create a php file called news_article.php (This must be the same name as the one you loaded in the Controller. Note that you do not need to include the php extension when loading it there.). In this file copy the following lines: <?php print $title; ?> <?php print $body; ?>

As you can see, the $title and the $body variables are being passed to the View from the Controller via the $data array. You can add all sorts of markup to display the page in any way you want but for our purposes, an H1 tag for the title and a paragraph for the body are enough. Save the file and point your browser to the Controller you just created: http://example.com/news/show/1
If the browser makes this request, CodeIgniter will now look for a Controller named news (in a php class file called news.php), call a method within it named show(), and pass it the parameter 1. This method will then load the news_model that queries the database and returns the piece of news which then the Controller passes to the View for display. Very simple and logical. If you go to http://example.com/news/show/2, it will display the piece of news with the ID equal to 2.

And here you have it: a basic but dynamic application that queries the database for information and displays it to the client. Now you may ask, why use 3 files and all these functions and configuration for this? Well the answer to this will be more than obvious when you build complex applications for which functional programming becomes difficult to manage and not using a framework like CodeIgniter will force you to define all these libraries yourself.
}

What this method does is the following: the first line loads the news_model we just created. The second one uses it and stores the query result (which is an associative array containing all the columns in the row) in the $news variable. The third and fourth lines store in the $data array the title and body of the retrieved news and the fifth one loads the View we want to use to display them and passes the information along. Each key in the $data array will represent a variable to be printed out in the View file. So let’s see how we build that.

The View


Navigate to the application/views folder and create a php file called news_article.php (This must be the same name as the one you loaded in the Controller. Note that you do not need to include the php extension when loading it there.). In this file copy the following lines:
<?php print $title; ?>
<?php print $body; ?>

As you can see, the $title and the $body variables are being passed to the View from the Controller via the $data array. You can add all sorts of markup to display the page in any way you want but for our purposes, an H1 tag for the title and a paragraph for the body are enough. Save the file and point your browser to the Controller you just created:
http://example.com/news/show/1

If the browser makes this request, CodeIgniter will now look for a Controller named news (in a php class file called news.php), call a method within it named show(), and pass it the parameter 1. This method will then load the news_model that queries the database and returns the piece of news which then the Controller passes to the View for display. Very simple and logical. If you go to http://example.com/news/show/2, it will display the piece of news with the ID equal to 2.

And here you have it: a basic but dynamic application that queries the database for information and displays it to the client. Now you may ask, why use 3 files and all these functions and configuration for this? Well the answer to this will be more than obvious when you build complex applications for which functional programming becomes difficult to manage and not using a framework like CodeIgniter will force you to define all these libraries yourself.

Comments

  1. Hey really nice blog.. truely helpful.. good one.. keep it up

    ReplyDelete

Post a Comment

Popular posts from this blog

Basic naming idea in codeigniter

File Naming Class files must be named in a Ucfirst-like manner, while any other file name (configurations, views, generic scripts, etc.) should be in all lowercase. INCORRECT: somelibrary.php someLibrary.php SOMELIBRARY.php Some_Library.php Application_config.php Application_Config.php applicationConfig.php CORRECT : Somelibrary.php Some_library.php applicationconfig.php application_config.php Furthermore, class file names should match the name of the class itself. For example, if you have a class named  Myclass , then its filename must be Myclass.php. Class and Method Naming Class names should always start with an uppercase letter. Multiple words should be separated with an underscore, and not CamelCased. INCORRECT : class superclass class SuperClass CORRECT : class Super_class class Super_class {           public function __construct ()        ...

How to setup CodeIgniter in your localhost with WAMP server

I've been developing a couple of website using codeIgniter framework. I only learned about this framework early this year 2011. Basically, I've tried installing codeIgniter from localhost and on the host server itself. How to make codeigniter work is very simple and easy. Below are the steps to kick start your first website using codeigniter. 1. Installing WAMP First and foremost, before you can have your website running on your localhost you should get a copy of WAMP(Windows Apache MySQL and PHP). It is where you can manage your server settings and Apache/MySQL services. So start downloading Wampserver now! As you can see there are 2 buttons to download between 32bits and 64bits that would be basing on your system type. To check what OS type is running click Windows logo on your keyboard + Pause/Break and a window will appear. After download, double click the file and follow the instructions given. Everything will be installed automatically  with the ...