CodeIgniter Basics

Everything You Need to Get Started With CodeIgniter

Tutorial Details
  • Difficulty: Beginner
  • Technology: PHP
Share

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.


Related Posts

Add Comment

Discussion 218 Comments

Comment Page 5 of 5 1 ... 3 4 5
  1. bellir says:

    How do I get my postings deleted?
    Is there a form that I should submit?
    tks
    bellir

  2. prakash says:

    superb……..

  3. rulhaf says:

    thank’s so much for this tut… :D
    very helpful for me… :)

  4. beschneider says:

    I’ve also problems with Step 8.
    “syntax error, unexpected ‘<', expecting T_STRING or T_VARIABLE [...] on line 7"

    When I leave out the span-tags, like said in the comments before, I get the message: "Unable to connect to your database server using the provided settings", even when I've created the helloworld view-file.

    Do the span-tags need to be in quotation marks?

    * write span-tags, 'cause the angle brackets aren't shown in the comments

  5. Koustubh says:

    Hi
    Very nice tutorial.

    I am getting following error while running this tutorial

    PHP Parse error: parse error, unexpected ‘<', expecting T_STRING or T_VARIABLE or '{' or '$' in C:\Inetpub\wwwroot\CodeIgniter\system\application\controllers\helloworld.php on line 7.

    can you please help me.

    Thanks.

  6. Neftali says:

    ok… im sorry just venting but i spent an hour trying to figure out why my view wasnt returning any results… i checked config files and app files against the demo only to realize it wasnt my file creation but your code logic… you wrote:

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

    and the conditional should be “if ($query->num_rows() < 1)" … or "if less than 1 row returned…then error"

    just wish you would have posted actual working code… would have saved me some frustration… and time

    oh well hope this helps others…

  7. asees says:

    it is very useful tutorial

  8. Oliver says:

    Why make a beginners tutorial that does not work!!! Its imperative that a simple helloworld tutorial be bug free otherwise you are giving a badname to CI.

    For the record the answer to why tutorial wasnt working was found within the comments. Have re-copied here:

    U need following correction:
    Step 1: Open controllers/helloworld.php
    Line 8: $data['result'] = $this->helloworld_model->getData();
    change to : $data['result'] = $this->helloworld_model->getData();
    Step 2: Open models/helloworld_model.php
    Line 15 : if ($query->num_rows() > 0)
    change to: if ($query->num_rows() == 0)

  9. Hanish Vohra says:

    Hi This is very good tutorial to start this framework but I got this problem in model.php file

    Call to a member function get() on a non-object in codeigniter

    Solution of this error is

    Change the
    $autoload['libraries'] = “”;

    to

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

    Thanks

  10. 1ukaz says:

    In the index() function of the controller, besides extending the Controller class; you forgot to call the parent constructor e.g: parent::Controller(); ribbit :-P

    To all those who keep asking for the error:
    “syntax error, unexpected ‘index_model->getData();

    By this times you should realize that:

    $this->helloworld_model->getData();

    Is not calling a method of any object … da ???

  11. 1ukaz says:

    The post comments, cut me off the tags; as expected. Could have made it with your codes :-P

  12. UltraBob says:

    In order to make this tutorial work it has to be modified as follows:

    (hopefully it doesn’t munge my code, no preview here it seems)

    In the controller:

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

    should be replaced with:

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

    As I was typing it in, I thought this me some weird convenience syntax, but it is just a bug.

    In the model:

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

    should be:

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

    bad form to get the logic exactly backwards here in a beginner tutorial.

    I know I’m a latecomer to this tutorial which is why it baffles me that it is still so error ridden. A complete beginner would be totally baffled by this. Someone with permission to do so, please fix the original tutorial.

  13. UltraBob says:

    OK, it did munge my first correction. The point is that <span class=”sql”> and </span> should be removed.

  14. Jiten says:

    hi All,

    I am not able to access a variable initialized in my controller file
    [code]
    class Hello extends Controller{
    function Hello(){
    parent::Controller();
    $this->myvar = 'Jiten';
    }
    function index(){
    //echo "Hello World !";
    $this->load->helper('url');
    $data['message'] = 'Hello World Again';
    $data['myvar'] = $this->myvar;
    $this->load->view('hello_view', $data);
    }
    }
    [/code]

    and accessed in view file

    [code]

    myApp
    <link rel="stylesheet" type="text/css" href='css/styles.css'/>

    [/code]

    Please if any one can highlight what is the problem in the code here.

  15. Jiten says:

    posting the view file code again

    myApp
    <link rel="stylesheet" type="text/css" href='css/styles.css’/>

  16. Rob Dean says:

    Why don’t you put the corrected code into the Article, save everyone the headache of learning the wrong way.

  17. gucci says:

    it is very useful tutorial,Thank you for sharing

    • kef says:

      i follow this tutorial but i didn’t get any out put. what is the problem. please help me
      my php /mysql version is 5.
      i am new in codeignetor framwork

  18. cooljaz124 says:

    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 !

  19. me says:

    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/”;

  20. dave says:

    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?

  21. Robin says:

    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…

  22. parmjeet says:

    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!’);
    }

  23. Chris says:

    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.

  24. Chris says:

    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.

  25. Sridhar says:

    Yeah!!!! Gr8.

  26. Hcalzada says:

    I’m from mexico,

    Congratulations for this tutorial is great!

    I learned a lot from this tutorial

    Thanks

  27. jon says:

    Thank you Chris your suggestion was good. Replacing

    <?=
    with
    <?php echo

    in helloworld_view.php solved my problem.

  28. Liaqat Ali says:

    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;?>

  29. thz says:

    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

  30. cm Designer says:

    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!

  31. caspar says:

    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 !

  32. Mike Smith says:

    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.

  33. Rory says:

    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!

Comment Page 4 of 4 1 2 3 4

Add a Comment

To add a code snippet to your comment, please wrap your code like so: <pre name="code" class="html">YOUR CODE</pre>. You can replace the class name with "js," "css," "sql," or "php." If there are any "<" or ">" within your code, please search and replace them with: &lt; and &gt; respectively.