Tutorial

CodeIgniter: Getting Started With a Simple Example

Published on July 24, 2013
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);
}

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.

CodeIgniter—Article #1

CodeIgniter—Article #2

CodeIgniter—Article #3

Article Submitted by: Danny

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


About the authors

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
10 Comments


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Thanks a lot for sharing your info. I really appreciate your efforts and I am waiting for your next post…

This information was useful for me.

You can delete these two lines too

$data['title'] = $news['title'];
$data['body'] = $news['body'];

and $this->load->view(‘news_article’, $news);

the name of columns as $nameofcolumn is OK.

Thanks & Good Codeigniter information provide.

Thank for your shareing

Could you zip example ?

This is a nice example to start with codeignitor but if someone is looking to start from the ZERO point of development process, then must have a look at this also http://www.13facts.info/getting-started-codeigniter-13facts/

Thanks

very nice neat and clean presentation of each and every point … a person who without knowing a knowledge of apache ,codeigniter and ubuntu can understand very well by this…

It’s awesome… You have provided a very good information. It is very useful for my students thank you. Great going. Kindly provide your other websites(if you have) to learn more on this kind of informations.

Website:  www.kaashivinfotech.com               http://inplanttrainingchennai.com/                internshipinchennai.in                http://inplanttraining-in-chennai.com/                inplant-training.org

Thanks for this introductory lesson on CodeIgniter. It really worked and I have a better idea for further exploring this wonderful framework

This comment has been deleted

    Try DigitalOcean for free

    Click below to sign up and get $200 of credit to try our products over 60 days!

    Sign up

    Join the Tech Talk
    Success! Thank you! Please check your email for further details.

    Please complete your information!

    Get our biweekly newsletter

    Sign up for Infrastructure as a Newsletter.

    Hollie's Hub for Good

    Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

    Become a contributor

    Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

    Welcome to the developer cloud

    DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

    Learn more
    DigitalOcean Cloud Control Panel