CodeIgniter Basics

Everything You Need to Get Started With CodeIgniter

Tutorial Details
  • Difficulty: Beginner
  • Technology: PHP

CodeIgniter is a web application framework for PHP. It enables developers to build web applications faster, and it offers many helpful code libraries and helpers which speed up tedious tasks in PHP. CodeIgniter is based on a modular design; meaning that you can implement specific libraries at your discretion – which adds to the speed of the framework. This tutorial will attempt to show you the basics of setting up the framework, including how to build a basic hello world application that uses the MVC approach.


Why a Framework?

Why a Framework?

Frameworks allow for structure in developing applications by providing reusable classes and functions which can reduce development time significantly. Some downsides to frameworks are that they provide unwanted classes, adding code bloat which makes the app harder to navigate.


Why CodeIgniter?

CodeIgniter Basics

CodeIgniter is a very light, well performing framework. While, it is perfect for a beginner (because
of the small learning curve), it’s also perfect for large and demanding web applications. CodeIgniter is developed by EllisLab and has thorough, easy to understand
documentation. Below is a list of reasons of what makes CodeIgniter a smart framework to use?

  • Small footprint with exceptional performance
  • MVC approach to development (although it is very loosely based which allows for flexibility)
  • Generates search engine friendly clean URLs
  • Easily extensible
  • Runs on both PHP 4 (4.3.2+) and 5
  • Support for most major databases including MySQL (4.1+), MySQLi, MS SQL, Postgres, Oracle, SQLite,
    and ODBC.
  • Application security is a focus
  • Easy caching operations
  • Many libraries and helpers to help you with complex operations such as email, image manipulation,
    form validation, file uploading, sessions, multilingual apps and creating apis for your app
  • Most libraries are only loaded when needed which cuts back on resources needed

Why MVC?

MVC

For starters, MVC stands for Model, View, Controller. It is a programing pattern used in developing
web apps. This pattern isolates the user interface and backend (i.e. database interaction from each other. A successful
implementation of this lets developers modify their user interface or backend with out affecting
the other. MVC also increases the flexibly of an app by being able to resuse models or views over
again). Below is a description of MVC.

  • Model: The model deals with the raw data and database interaction and will contain functions
    like adding records to a database or selecting specific database records. In CI the model
    component is not required and can be included in the controller.
  • View: The view deals with displaying the data and interface controls to the user with.
    In CI the view could be a web page, rss feed, ajax data or any other “page”.
  • Controller: The controller acts as the in between of view and model and, as the name suggests,
    it controls what is sent to the view from the model. In CI, the controller is also the place to load libraries and helpers.

An example of a MVC approach would be for a contact form.

  1. The user interacts with the view by filling in a form and submitting it.
  2. The controller receives the POST data from the form, the controller sends this data to the model
    which updates in the database.
  3. The model then sends the result of the database to the controller.
  4. This result is updated in the view and displayed to the user.

This may sound like alot of work to do. But, trust me; when you’re working with a large application, being able to reuse models or views saves a great deal of time.


Step 1: Downloading CodeIgniter

Too start off you will need to download CodeIgniter and upload it to your server. Point your browser
to http://www.codeigniter.com/ and
click the large download button. For this tutorial we are using version 1.70.


Step 2: Installing and Exploring CodeIgniter

Once you have downloaded CodeIgniter, all you need to do is unzip it, and rename the “CodeIgniter_1.7.0″ folder to
either the application name or, in this case, “ci” and upload it to your PHP and MySQL enabled server.
Now that its on your server, I’ll explain what all the folders and files are for:

  • The system folder stores all the files which make CI work.
    • The application folder is almost identical to the contents of the system folder
      this is so the user can have files that are particular to that application, for example if a
      user only wanted to load a helper in one application he would place it in the system/application/helpers folder
      instead of the system/helpers folder.

      • The config folder stores all the config files relevant to the application. Which
        includes information on what libaries the application should auto load and database details.
      • The controllers folder stores all the controllers for the application.
      • The errors folder stores all the template error pages for the application. When
        an error occurs the error page is generated from one of these templates.
      • The helpers folder stores all the helpers which are specific to your application.
      • The hooks folder is for hooks which modify the functioning of CI’s core files,
        hooks should only be used by advanced users of CI
      • The language folder stores lines of text which can be loaded through the language
        library to create multilingual sites.
      • The libraries folder stores all the libraries which are specific to your application.
      • The models folder stores all the models for the application.
      • The views folder stores all the views for the application.
    • The cache folder stores all the caches generated by the caching library.
    • The codeigniter folder stores all the internals which make CI work.
    • The database folder stores all the database drivers and class which enable you to
      connect to database.
    • The fonts folder stores all the fonts which can be used by the image manipulation library.
    • The helpers folder stores all of CI’s core helpers but you can place your own helpers
      in here which can be accessed by all of your applications.
    • The language folder stores all of CI’s core language files which its libaries and helpers
      use. You can also put your own language folders which can accessed by all of your applications.
    • The libaries folder stores all of CI’s core libaries but you can place your own libraries
      in here which can be accessed by all of your applications
    • The logs folder stores all of the logs generated by CI.
    • The plugin folder stores all of the plugins which you can use. Plugins are almost identical
      to helpers, plugins are functions intended to be shared by the community.
    • The scaffolding folder stores all the files which make the scaffolding class work.
      Scaffolding provides a convenient CRUD like interface to access information in your database
      during development.
  • The user_guide houses the user guide to CI.
  • The index.php file is the bit that does all the CI magic it also lets the you change the
    name of the system and application folders.

Step 3: Configuring CodeIgniter

Getting CI up and running is rather simple. Most of it requires you to edit a few configuration
files.

You need to setup CI to point to the right base URL of the app. To do this, open up system/application/config/config.php and
edit the base_url array item to point to your server and CI folder.

$config['base_url'] = "http://localhost/ci/";

Step 4: Testing CodeIgniter

We’ll do a quick test to see if CI is up and running properly. Go to http://localhost/ci/ and you
should see the following.


Step 5: Configuring CodeIgniter Cont.

If you’re up and running, we should finish the configuration. We are starting to configure it specifically for our new helloworld app. If you want to use a database with your application, (which in this tutorial we do.) open up system/application/config/database.php and set the following array items to there corresponding values. This code connects to a MySQL
database called “helloworld” on a localhost with the username “root”, and the password, “root”.

$db['default']['hostname'] = "localhost";
$db['default']['username'] = "root";
$db['default']['password'] = "root";
$db['default']['database'] = "helloworld";
$db['default']['dbdriver'] = "mysql";

Additionally, since we will be using the database quite a bit, we want it to auto load so that we don’t
have to specifically load it each time we connect. Open the system/application/config/autoload.php file
and add ‘database’ to the autoload libaries array.

$autoload['libraries'] = array('database');

Currently, the CI setup will have a default controller called “welcome.php”; you can find this in the system/application/controllers folder. For this tutorial, delete it and open your system/application/config/routes.php file. Change the default array item to point to the “helloworld” controller.

 $route['default_controller'] = "Helloworld"

CI also has a view file that we do not need. Open up the system/application/view/ folder
and delete the welcome_message.php file.


Step 6: Create the Helloworld Database

As this isn’t really a tutorial on MySQL, I’ll keep this section as short as possible. Create a database called “helloworld” and
run the following SQL through phpMyAdmin (or similar MySQL client).

CREATE TABLE `data` (
  `id` int(11) NOT NULL auto_increment,
  `title` varchar(255) NOT NULL,
  `text` text NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;

INSERT INTO `data` (`id`, `title`, `text`) VALUES(1, 'Hello World!', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla 
sapien eros, lacinia eu, consectetur vel, dignissim et, massa. Praesent suscipit nunc vitae neque. Duis a ipsum. Nunc a erat. Praesent 
nec libero. Phasellus lobortis, velit sed pharetra imperdiet, justo ipsum facilisis arcu, in eleifend elit nulla sit amet tellus. 
Pellentesque molestie dui lacinia nulla. Sed vitae arcu at nisl sodales ultricies. Etiam mi ligula, consequat eget, elementum sed, 
vulputate in, augue. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae;');

Step 7: Create the Helloworld Model

Models are optional in CI, but it’s considered best practice to use them. They are just PHP classes that contain
functions which work with information from the database. Go
ahead and make a helloworld_model.php file
in the system/application/models folder.
In this file, create a Helloworld_model class, Helloworld_model construct and a function called getData.

In the getData function we are
going to use Active Record database functions which speed up database development times when working
with CI and databases. Essentially, they are simplified functions to create queries.

<?php
class Helloworld_model extends Model {

    function Helloworld_model()
    {
        // Call the Model constructor
        parent::Model();
    }
    
    function getData()
		{
			//Query the data table for every record and row
			$query = $this->db->get('data');
			
			if ($query->num_rows() > 0)
			{
				//show_error('Database is empty!');
			}else{
				return $query->result();
			}
		}

}
?>

Step 8: Create the Helloworld Controller

Let’s create a controller that will display the view, and load the model. That way, when
you go to the address http://localhost/ci/index.php/helloworld/, you will see the data from the database.
In the folder system/application/controllers, create a file called helloworld.php.
In this new file, we’ll create a class which has the same name as the file.

Within this class, you need to create a function called “index”. This is the function that will be
displayed when no other is provided – e.g. when http://localhost/ci/index.php/helloworld/ is
visited. If, for example, we created a function called foo, we could find this as http://localhost/ci/index.php/helloworld/foo/.

The key thing to remember is how CI structures its URLs; e.g http://host/codeignitordirectory/index.php/class/function.

In the controller index function, we need to load the model, query the database, and pass this queried
data to the view. To load any resources into CI e.g. libraries,
helpers, views, or, models, we use the load class. After we have loaded the model, we can access it through
its model name and the particular function. To pass data to a view we need to assign it to an array
item and pass the array – which recreates the array items as a variable in the view file.

<?php
	class Helloworld extends Controller{
		function index()
		{
			$this->load->model('helloworld_model');

			$data['result'] = $this->helloworld_model->getData();
			$data['page_title'] = "CI Hello World App!";

			$this->load->view('helloworld_view',$data);
	    }
	}
?>

If we visited http://localhost/ci/index.php/helloworld/ now, it wouldn’t work; this is because the view file does not exist.


Step 9: Create the Helloworld View

The view file is what the user sees and interacts with, it could be a segment of a page, or the whole page. You can pass an array of variables to the view through the second argument
of the load model function. To make the view for our tutorial, create a new file called helloworld_view.php in the system/application/view folder. Next, we just need to create our normal html, head
and body elements, and then a header and paragraph for the information from the database. To display all
the records received from the database, we put it in a “foreach” loop
which loops through all the elements.

<html>
	<head>
		<title><?=$page_title?></title>
	</head>
	<body>
		<?php foreach($result as $row):?>
		<h3><?=$row->title?></h3>
		<p><?=$row->text?></p>
		<br />
		<?php endforeach;?>
	</body>
</html>

You may have noticed that we are using php alternative syntax, this provides an convenient and time
saving way to write echo statements.


Step 10: Ta-da and Some Extras

When you visit “http://localhost/ci/index.php/helloworld/”, you
should see something similar to this.

But we aren’t done yet. There are a few things you can do to improve your CodeIgniter experience -
like removing that annoying index.php bit out of the URL. You can accomplish this task by creating a .htaccess file in the root folder, and adding the following code.

RewriteEngine on
RewriteCond $1 !^(index\.php|images|robots\.txt)
RewriteRule ^(.*)$ ci/index.php/$1 [L]
        

You’ll also need to open up the config.php file in system/application/config/ and edit the index_page array item to a blank string.

$config['index_page'] = ""; 

Another nifty trick is to turn on CI’s ability to parse PHP alternative syntax if its
not enabled by the server. To do this, open up the same file as before, system/application/config/config.php, and set the rewrite_short_tags array item to TRUE.

$config['rewrite_short_tags'] = TRUE;

I hope all goes well! Look forward to seeing more CodeIgniter tutorials from me in the future.

  • Subscribe to the NETTUTS RSS Feed for more daily web development tuts and articles.


Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • Pingback: PHP Developer CodeIgniter MVC Framework | Freelance PHP Developer

  • http://www.cooljaz124.com cooljaz124

    Im not sure why such carelessness. This is such a famous site and the simple thing is not bug free. Not even updated !! Very pathetic !

  • me

    Parse error: syntax error, unexpected ‘:’ in C:\xampp\htdocs\codeigniter\system\application\config\config.php on line 14
    How i fix this error??

    Line 14 is
    $config['base_url'] = “http://localhost/codeigniter/”;

  • dave

    never seen a helloworld with so much bugs, it make a bad reputation to php developers
    why didn’t you take time to run it 5 minutes?

  • Robin

    Hi All,

    I still can’t view the database result.
    I already followed the corrections :

    First, Step 8 – Line 15
    if ($query->num_rows() > 0)

    should be LESS than, not greater than:
    if ($query->num_rows() db->get(‘data’);

    and the autoload.php already set to database

    The result is as follows :

    title?>

    text?>

    Where do I still fix?

    BR…

  • http://vinove.com parmjeet

    Great tutorial.But the model code
    if ($query->num_rows() > 0)
    {
    //show_error(‘Database is empty!’);
    }else{
    return $query->result();
    }
    Should be in reverse:
    if ($query->num_rows() > 0)
    {
    return $query->result();
    }else{
    show_error(‘Database is empty!’);
    }

  • http://www.studio625.net/ Chris

    Any chance you might update this post with corrected code? Most people don’t read the comments to find the working code for a tutorial.

    Also, if you’re getting useless output like this:
    title?>
    text?>

    You can fix it by replacing each instance of
    <?=
    with
    <?php echo
    in helloworld_view.php

    The shorthand syntax is nice, but you have to enable it in your PHP configuration, which might not be worth the hassle for a simple tutorial like this.

    • Proff

      WOW Chris, you taught me how to fix my issue! Thanks buddy, I spent hours on this with no avail. Thank god for the comments! Take care.

  • http://www.studio625.net/ Chris

    Actually, using PHP shorthand is officially discouraged because of potential XML parsing conflicts. I found this comment in my php.ini:

    ; This directive determines whether or not PHP will recognize code between
    ; tags as PHP source which should be processed as such. It’s been
    ; recommended for several years that you not use the short tag “short cut” and
    ; instead to use the full tag combination. With the wide spread use
    ; of XML and use of these tags by other languages, the server can become easily
    ; confused and end up parsing the wrong code in the wrong context. But because
    ; this short cut has been a feature for such a long time, it’s currently still
    ; supported for backwards compatibility, but we recommend you don’t use them.

  • Sridhar

    Yeah!!!! Gr8.

  • Hcalzada

    I’m from mexico,

    Congratulations for this tutorial is great!

    I learned a lot from this tutorial

    Thanks

  • jon

    Thank you Chris your suggestion was good. Replacing

    <?=
    with
    <?php echo

    in helloworld_view.php solved my problem.

  • Liaqat Ali

    Hi All, I am Developing a web site. my below code work perfectly. but i have a problem i want “$statsid” above the second foreach, i want to pass this as variable or id to controller to get the data from table where equls to this “$statsid”

    result() as $rows):?>

    <img src="config->item(‘base_url’).$rows->profile_picture_path;?>” />

    user_name;?> description;?>
    <a href="#nogo" id="status_id;?>” class=”image_title” />Comments

    status_id; ?>

    result() as $rs):?>

    <img src="config->item(‘base_url’).$rows->profile_picture_path;?>” />

    user_name;?> status_comment;?>

  • http://net.tutsplus.com/tutorials/php/codeigniter-basics/ thz

    let me compile the files.

    helloworld_model.php – use the code below

    db->get(‘data’);

    //if ($query->num_rows() > 0)
    if ($query->num_rows() result();
    }
    }

    }
    ?>

    helloworld.php (controller) – use the code below

    load->model(‘helloworld_model’);
    //$data['result'] = $this->helloworld_model->getData();
    $data['result'] = $this->helloworld_model->getData();
    $data['page_title'] = “CI Hello World App!”;

    $this->load->view(‘helloworld_view’,$data);
    }
    }
    ?>

    helloworld_view.php – use the code below

    title;?>
    text;?>

    ta da!
    thanks for the tutorial and thanks for the those fixed the tutorial :D

  • http://cmdesign.ca cm Designer

    Simple tut and very usefull.

    No time to read huge books and watch video to find out how it works.

    Thanks, thanks, thanks.

    Just what I need right now.

    I am very happy!

  • caspar

    I think your work is fabulous ! Just why to let code with mistakes ? Almost for new users ?
    They will get mad for sure like me ! Make it simple and understandable for beginners !

  • Mike Smith

    I have to say this tutorial was pants, so many errors and omissions have made my first step into CI worthless and it was a hello world app for God’s sake.

  • Rory

    Extremely dissapointing tutorial, code that doesnt work php short-tags. Would it be too much trouble to update this tutorial to make it functional without reading through the comments!

  • http://www.muhamadsholeh.com sholeh

    good for beginer like me…

  • Pingback: CodeIgniter Web Page Caching – Achieve performance that nears that of static web pages! « Deadlyfingers

  • http://www.dk-unlocked.co.cc Deepesh Kapadia

    Hi Im getting the following error

    A PHP Error was encountered

    Severity: Warning

    Message: Invalid argument supplied for foreach()

    Filename: views/helloworld_view.php

    Line Number: 6

    Anyone knows how to fix this?

  • Derek Davis

    1. In the model file replace

    if ($query->num_rows() > 0)
    {
    //show_error(‘Database is empty!’);
    }else{
    return $query->result();
    }

    WITH

    if ($query->num_rows() > 0)
    {
    return $query->result();
    }else{
    show_error(‘Database is empty!’);
    }

    2. In the controller file replace

    $data['result'] = $this->helloworld_model->getData();

    WITH

    $data['result'] = $this->helloworld_model->getData();

    3. In the view file replace all &lt?= WITH &lt?php

    4. In the view file place the word echo in front of the variables that are to be displayed :

    echo $page_title
    echo $row-&gttitle
    echo $row-&gttext

    • Derek Davis

      Please Delete. The other below is correct

  • Derek Davis

    1. In the model file replace

    if ($query->num_rows() > 0)
    {
    //show_error(‘Database is empty!’);
    }else{
    return $query->result();
    }

    WITH

    if ($query->num_rows() > 0)
    {
    return $query->result();
    }else{
    show_error(‘Database is empty!’);
    }

    2. In the controller file replace

    $data['result'] = $this->helloworld_model->getData();

    WITH

    $data['result'] = $this->helloworld_model->getData();

    3. In the view file replace all <?= WITH <?php

    4. In the view file place the word echo in front of the variables that are to be displayed :

    echo $page_title
    echo $row->title
    echo $row->text

  • Braca

    im still getting the error

    Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\system\application\views\helloworld_view.php on line 6

  • Eddy

    Hello im getting no output at all
    I did all the fixes.

    helloworld.php
    changed to : $data['result'] = $this->helloworld_model->getData();

    helloworld_model.php
    changed to: if ($query->num_rows() == 0)

    and allowed short tags.

    Still the screen is blank any clue?
    running Xamp…

  • Swapnil kumbharm,KRD

    I like Your CI notes
    But i want ADD,UPDATE,DELETE,VIEW application in CI In simple code

  • http://www.professionalsofttech.com James

    I want to process GET parameters submitted through form in codeigniter. How to do this?

  • http://www.acidartstudio.com Rares

    Very usefull intro to CodeIgniter, thank you very much!

  • clustersblue

    Most of the information here are new to me. Thanks for sharing!

  • pingloopback

    Not working. Maybe I miss the step :(

  • phpcoder

    also, if you don’t have short tags enabled in your php.ini, you must replace the “<?=" with "<?php echo " i n the helloworld_view.php in the views folder, otherwise you won't see valid output from the database.

    Hopes this helps.

    • phpcoder

      I like to update my previous comment:

      Prior to getting to this last part of the tutorial:

      “Another nifty trick is to turn on CI’s ability to parse PHP alternative syntax if its
      not enabled by the server. To do this, open up the same file as before, system/application/config/config.php, and set the rewrite_short_tags array item to TRUE.
      view plaincopy to clipboardprint?”

      1. $config['rewrite_short_tags'] = TRUE;

      you need to replace “<?=" WITH "<?php echo"

      to get valid output.

  • Pingback: User Profile URLs « Kyle Gawley | Design Blog

  • mz

    Thanks php coder :)

    try this in helloword_view.php

    title;?>
    text;?>

    after I could see the output

  • Pingback: CodeIgniter, Zend Framework ve Symfony PHP Frameworkler’in tanıtımı | Tayfun Öziş Erikan

  • snow white

    this one is so great!
    this is actually my first time to work with/try framework and i’m so happy it worked at my first try!
    well, simply means that this tutorial is truly reliable..

    thanks a lot!

  • Pingback: 30+ Awesome CodeIgniter Tutorials for all Skill Levels | FlexLib

  • Pingback: 30+ Awesome CodeIgniter Tutorials for all Skill Levels | TheBestchoise.com

  • Pingback: 30+ Awesome CodeIgniter Tutorials for all Skill Levels | The best Tutorials

  • Pingback: 30+ Awesome CodeIgniter Tutorials for all Skill Levels | Megomarket.com

  • http://www.mkgnumb.com vorachate

    Need edit the autoload.php in ci/config/

    $autoload['libraries'] = array(‘cart’, ‘database’);

  • Pingback: Kodstok » Blog Archive » Code Tutorials : 30+ Awesome CodeIgniter Tutorials for all Skill Levels

  • Pingback: 30+ Awesome CodeIgniter Tutorials for all Skill Levels | Links.d2zone

  • http://www.nowwitwiz.co.za nowitwiz

    how do i add a form to enter, edit, and delete title, and text into the database

  • Ndaru

    Found some errors on your tutorial:

    1) helloworld_model.php, line 15:

    if ($query->num_rows() > 0)

    should be:

    if ($query->num_rows() == 0)

    2) helloworld.php, line 7:

    $data['result'] = $this->helloworld_model->getData();

    should be:

    $data['result'] = $this->helloworld_model->getData();

  • Pingback: 30+ Awesome CodeIgniter Tutorials for all Skill Levels | 中文IT博客聚合

  • Pingback: Looking for someone to help assist with coding?

  • Pingback: Top CodeIgniter Tutorials for New CodeIgniter Developers | gotphp.com

  • BOON TEONG

    Thank ….

  • http://feedastudent.com jerryLee

    I can only assume you mean for the database.php file to be under application/config/database.php and not system/application……
    That is where i found it anyway. Am I correct, or is something else going on?

  • Pat

    Anyone who’s just downloaded CI 2.0 and trying to work through this tut, the class construction methods have changed. You’ll need:

    <?php
    class Helloworld extends CI_Controller{

    function __construct()
    {
    parent::__construct();
    }

    function index()
    { //…etc

    and

    <?php
    class Helloworld_model extends CI_Model {

    function Helloworld_model()
    {
    // Call the Model constructor
    parent::__construct();
    }

    function getData()
    {//…etc

    Hope that saves someone the time I wasted :)

    Cheers for the tut.

    • sarah

      thank you!!

    • jeetu

      First thing is i am new one ,
      i do all above configuration but still it shows error
      will you please fix this problem please
      the error will looks like this ok.
      Fatal error: Class ‘Controller’ not found in D:\wamp\www\CodeIgniter_2.0.2\application\controllers\helloworld.php on line 2

      • Bunty

        use
        class Helloworld extends CI_Controller{

        }

        and

        class Helloworld_model extends CI_Model {

        }

        You used only Controller. That will be CI_Controller, and Model will be CI_Model .ok the error will remove.

    • Pushparaj

      Thank s lot ..very much useful for beginners and i have gained from your post.

  • http://www.thegreatvideos.com Anand Patel

    Any body knows the how to use GD library with Code Igniter ?