I have already written a few articles on Codeigniter; however, I haven’t written for genuine beginners yet. But, as i have written many beginner level tutorials here, i think, a beginners tutorial on codeigniter will be also helpful for my blog readers. At the time of writing, the latest codeigniter version is 2.0.2. I am going to use this version for today’s tutorial. This tutorial is intended for developers who are absolute beginners on Codeigniter and want to have a better start very quickly.
Prerequisites:
However, before using Codeigniter, you must know the MVC design pattern. To learn more about MVC, you can start with the wiki article on MVC.
Also, wish you have xampp/wamp or something similar already set up on your computer. Now, Download the latest version of codeigniter. extract it and copy the directory to the root of your local server. without doing anything else, you should be able to run this and see a page like as follows from this local URL: http://localhost/codeigntier/
Read The Complete PHP CodeIgniter Tutorials Series By CodeSamplez.com
Directory Structure:
The application directory structure is mainly consists of 2 directory, ‘system’ and ‘application’.
The ‘system’ directory is the core and consists of the core framework files. When a new version is released, you can update your existing application just by replacing this system directory with the latest release. We will never going to work on this folder ourselves. All our codes are going to take place in the ‘application directory’. There, you will see a list of subdirectories as like the following image:
Let’s get a little familiar with the directories:
- Cache: If you are using caching, this directory will contain all kinds of cached files. However, you may need to provide write access for the application to this directory, as Codeigniter will need to create temporary files in this folder. To learn how to use caching, please refer to the Codeigniter caching tutorial.
- Config: This directory includes settings/configuration-related information like database settings, route information, constants declaration, items to be auto-loaded, etc. To learn more, please visit Codeigniter documentation about using the config class.
- Controller: This directory includes all controller definitions. It can be said to be the entry point of the application; every request triggers a certain method of a controller.
- Core: If we need to extend the functionality of any core classes like controller,loader,router, etc., we can declare a new class here that will extend those core classes and put the implementation inside those.
- Errors: This directory includes a basic template for showing various kinds of errors, such as DB errors, PHP errors, 404 errors, etc., which we can change later as per our requirements.
- Helpers : This directory will include all helper files. Read more about using helpers.
- Hooks : This directory will include all hooks declarations. Read more about using hooks
- Language : This directory will include language files. By loading different language files, we can make our application multilingual supported. Read more about using language class.
- Libraries : This directory will include all library class files that might need to be created for our applications.
- Logs : This directory will include all application logs. To know how to write a log for debug/error/info, please learn more about error handling
- Migrations : This directory will include migration helpers.
- Models : This directory will include all model classes used in our application. This section can be said as the ‘data access layer’ of our application.
- Third_party: This directory will include library files, but only those imported from third parties. So, the difference between ‘third_party’ and ‘libraries’ is that one is for self-made libraries, one is for app-specific libraries, and the other is for importing party libraries.
- Views : This directory will include all view template files.
Application URL Structure:
Codeigniter uses a very easy and handy url structure scheme. and it is completely inter-related with the controller class name and method name. to access a controller method, you have to use url like {root_url}/index.php/{controller_name}/{method_name}. To learn more details, please refer to the Codeigniter URL structure documentation .
Create A Basic Controller:
Let’s start by making a basic controller class file. Create a new file in the ‘controllers’ directory and name it ‘blog.php.’ Here is the code snippet for this controller class:
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Blog extends CI_Controller {
/**
* Index Page for this controller.
*
* Maps to the following URL
* http://example.com/index.php/blog
* - or -
* http://example.com/index.php/blog/index
* - or -
* So any other public methods not prefixed with an underscore will
* map to /index.php/blog/{method_name}
* @see http://codeigniter.com/user_guide/general/urls.html
*/
public function index()
{
echo "Hello World";
}
}
/* End of file Blog.php */
/* Location: ./application/controllers/blog.php */
Code language: PHP (php)
Now, run the application with the URL “http://localhost/ci_app/index.php/blog.” You will see the sentence ‘Hello World’ on the page. ‘index is the default method that is executed when no other method is specified in the URL. We understood one thing clearly: to create a page, we may ignore having a model and/or a view file, but we just need a controller.
Create a model :
Let’s create a simple model for our application. We won’t cover any database activity in this tutorial. But it’s pretty easy. Set up your database server info on the ‘config/database.php.’ Then, you can access the database either straightway or by using the codeigniter-provided ‘active record’ library, which helps a lot in creating/executing SQL queries easily. You can read more about the Codeigniter active record class in my other article. Here is the code of the model class we will be using:
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Blogmodel extends CI_Model{
/**
* returns a list of articles
* @return array
*/
function get_articles_list(){
$list = Array();
$list[0] = (object)NULL;
$list[0]->title = "first blog title";
$list[0]->author = "author 1";
$list[0] = (object)NULL;
$list[1]->title = "second blog title";
$list[1]->author = "author 2";
return $list;
}
}
?>
Code language: PHP (php)
Modify The Controller:
To use the data from the model, let’s change our controller code, which will receive data from the model and send it to the view for final rendering. Here is the modified version of the controller:
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Blog extends CI_Controller {
public function index()
{
$this->load->model("blogmodel");
$articles = $this->blogmodel->get_articles_list();
$data["articles"] = $articles;
$this->load->view('blog/index',$data);
}
}
Code language: PHP (php)
Create A View:
Let’s create a simple view file that will show the data we get from the ‘blogmodel’ in a basic HTML template. Following is the template code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Welcome to Blog Page</title>
<style type="text/css">
body {
background-color: #fff;
margin: 40px;
font-family: Lucida Grande, Verdana, Sans-serif;
font-size: 14px;
color: #4F5155;
}
a {
color: #003399;
background-color: transparent;
font-weight: normal;
}
h1 {
color: #444;
background-color: transparent;
border-bottom: 1px solid #D0D0D0;
font-size: 16px;
font-weight: bold;
margin: 24px 0 2px 0;
padding: 5px 0 6px 0;
}
code {
font-family: Monaco, Verdana, Sans-serif;
font-size: 12px;
background-color: #f9f9f9;
border: 1px solid #D0D0D0;
color: #002166;
display: block;
margin: 14px 0 14px 0;
padding: 12px 10px 12px 10px;
}
</style>
</head>
<body>
<h1>Welcome To my blog</h1>
<?php
foreach($articles as $article)
{
?>
<h3><?php echo $article->title; ?></h3>
By <strong><?php echo $article->author; ?></strong>
<?php
}
?>
</body>
</html>
Code language: HTML, XML (xml)
Calling a view from the controller:
The above “Modify The Controller” already demonstrates how to call a view. However, there are a few things you will need to remember. A traditional codeigniter view is a simple php file with “.php” extension. You can place it anywhere inside the “views” directory. , you will have to mention the correct path inside the ‘views’ directory. Like if you have a view inside a “blog” directory(which resides in ‘views’ directory, of course). Then, you will have to pass the view parameter as follows:
$this->load->view("blog/template_name");
Code language: PHP (php)
Notice that we haven’t used any extension(here .php) for the template name, as it recognizes it automatically.
Another important thing to remember is that the second parameter is optional when calling the view. If you have any data to pass to the view, then pass it through the second parameter. If you don’t, then you won’t have to pass any second parameter at all.
Also, data that are passed to view are parsed from the associated array. Let’s say we are assigning and passing some data from the controller to view. The controller code is as follows:
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Test extends CI_Controller {
public function index()
{
$data["name"] = "Md Ali Ahsan Rana";
$data["designation"] = "Software Engineer";
$this->load->view('test',$data);
}
}
Code language: PHP (php)
The view code is as follows:
<!-- File name: test.php -->
<!-- Location: application/views/test.php -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Welcome to Test Page</title>
</head>
<body>
<h2>My Name is <?php echo $name; ?></h2>
<h2>My Designation is <?php echo $designation; ?></h2>
</body>
</html>
Code language: HTML, XML (xml)
Notice that every associative key from $data becomes a variable in the view section. So, for any data variable you may need on your view, you will have to wrap it with a common variable’s associative index(here $data variable) and finally pass this wrapper variable. Codeigniter will parse it automatically to its corresponding component variables.
References:
As long as you know the basics, the best place to learn everything in detail is the Codeigniter documentation. There, you will find details about everything with examples. I found it to be one of the best documentation on the web. You can ask any kind of question-related to Codeigniter on their official forum.
Also, don’t forget to check out my Codeigniter tutorials series for detailed tutorials with examples on various specific areas of this popular framework! Happy coding 🙂
Chuck says
First example works but the rest of the examples are lacking file names, etc. so not of much use as a beginner tutorial.
Rana says
Are you having issues? Can you please explain what? Then I can try to solve it and also update the tutorial for being more helpful for future seekers. Thanks..
francis says
Thanks for this…Like it
as says
Nice One. Thanks..
talentedaamer says
the name of the file should be similar to its class name,
for example if we have a class blog the controller should be blog.php this way you will not get error.
Gokul Raj says
How to create new controller.
Rana says
Hi, Please refer to “Create A Basic Controller” section. Please let me know f you don’t understand anything..
Gokul Raj says
Thanks Rana. Then i have another doubt how to create admin for cms. I created admin folder in controller. If i typed browser i have error page not found. What i do Rana.
Rana says
Hi, well, you will have to study a little about how codeigniter urls work and also how you can customize the routing. Please refer to https://codesamplez.com/development/codeigniter-routes-tutorial and its references to codeigniter user guide for details. Finally, seems like, you are facing issue similar to this one: http://stackoverflow.com/questions/8143997/codeigniter-2-0-x-controller-subdirectories-default-controller-needs-to-be-in . There is a solution already, refer to that. Hope these helps. Thanks.
suresh says
that’s good
MichaelB says
The first section does work, then the rest of the article becomes unclear.
1. In the section “Create a model”, what should be the filename of that file?
2. In the section “Create A View”, what should be the filename of that?
Rana says
Hi MichaelB, There is no specific restriction to the naming convention for model/view(or even controller). You can use any name, just you will have to remember to extend them from their corresponding base class. Like, if you are creating a model, you must have to inherit the “CI_Model” class, to get the characteristics of a regular Codeigniter model. In case of view, just name the template any name and then call it from controller with data(if any), Like as follows:
$this->load->view(“template_name”,$data);
I will edit the tutorial for calling a view from controller. Seems it will may helpful to some other guys like you. Thanks for pointing out is.
ITGuy says
Really great programming abilities you\’ve there. i\’m a programmer myself but I still require to learn until I reach your ability. great article!
best free web services says
Wow, nice post buddy. It can help me to develop website using codeigniter framework.
Haider says
thank you very much
it give me complete inside out to the MVC as well as codeignighter
thanks you very very much
kvkbharadwaz says
this helped me a lot buddy and moreover your site interface is really good and CLEAN.
keep up the good work.
bari says
hi rana, i have problem with include php file. i use include(), require() and require_once(). but none of them works.
i have a php file that contain only variables, so much variables. and i want to include the file to passing variables.
how i supposed to do. pls help me.
the ci directory:
-application
-system
-user_guide
-style
-include_folder
and my file in include_folder directory.
thanks in advance.
Rana says
try using:
APPPATH.”/include_folder/file_name.php”
balaji says
it vary good for fresher + inretmideate
kamal says
hello Rana,
I’m a beginer in CI my problem is how to load jquery library in the current version of CI and how to apply a common CSS styling sheet to all my views
Jhon says
Thanx Rana for providing these Tuts these are very useful for everyone especially fresher
pratik says
great,i have one problem i want to pass the more then one query from the model and get in controller.now i want to some additional work on that query and pass to the view.how can i do that.thanks
john says
Very useful especially on passing data to the view and how the keys of the associative array are automatically turned into variables in the view.
julieancordova says
what would be the best IDE for code igniter?
where I can use breakpoints,
Raza says
the first program for blog.. throws an error more of a warnin. creating default object on empty value..
Md Ali Ahsan Rana says
Hello Raza, it seems like you php compatibility error. This exercize was written with php 5.3.x and you are probably using php 5.4 , right? Just initialize all the variables at first (example: $test = (object)NULL) solves the problem in most cases. If you are still not sure what to do, can you give the error line number or a screenshot link? Thanks.
Nadimuthu says
How to configure with lamp? Anyone please help me..
Azhar says
i have this problem. I have created a views/templates/navbar.php using bootstrap. the bootstrap is located in the root directory assets/bootstrap. I called the navbar.php through the default controller (news). It works.
Then I create another views/templates/page.php. I created a function create_cosec in the default controller with $this->load->view(‘navbar’); and $this->load-view(‘page.php’); . I wish the page will display the navbar on the top follow by the page details.
When I call the page localhost/index.php/news/ create_cosec ==>the page is display correctly but the navbar displayed but without the bootstrap functionalities. It seems that codeigniter doesn’t know where is the assets/bootstrap directory?
Is it URL issues?
Thanks
D R says
Good framework to work with, also believe in learning the pure php language too, and also try to learn other frameworks so that you keep yourself on top of development.
Lucky Bhumkar says
Good explanation..but lacks screenshots.
Michael says
How about some explanation of the root folders like “Source files”… what other folders are at this level? I’m looking at it from a continuous deployment point of view.
mwamba says
its giving error
A PHP Error was encountered
Severity: Warning
Message: Creating default object from empty value
Filename: models/blogmodel.php
Line Number: 12
in the list model
Md Ali Ahsan Rana says
That is because of php version, I assume. Should be fixed by using ‘$list = (object)NULL;’ . Hope this helps.
Lilly says
Excellent Tutorial !! Helps alot.
bakhtiar khan wazir says
Good and understandable tutorial
Malik Ahmad says
Thanks for tutorial 🙂
so nice
Sandeep says
Hi Md Ali Ahsan Rana,
I’m getting an error “fetching ajax content” when i run my application in my local server xammp and also getting error each time when i refresh the pages of my project.
waiting for your response
thanks!
Md Ali Ahsan Rana says
There isn’t any ajax related code been shared on this tutorial. So, I am assuming, you are trying in a little different way. Thus I will suggest you to share your code/more info in some kind of code sharing site and put the link here. This will help to understand your issue more better.
Tharindu Dissanayake says
nice tutorials.. thanks Mr.Rana
skemas says
have entered $list = (object)NULL; but returns an errror:
Fatal error: Cannot use object of type stdClass as array in C:\xampp\blog\codeigniter\application\models\blogModel.php on line 13
Where should i place the line of code? Thanks! Greate tutorial for beginners
Md Ali Ahsan Rana says
I guess, that’s because of your PHP version. You can try with ‘Array()’/’array()’ instead of ‘(object)NULL’, if you are using older versions of PHP. Hope that helps.
Syed Sajid Ali says
Please tell me how we load multiple pages in ci
Saranya Mani says
Hi,
I am Saranya.
I worked lot on CMS, i want to learn Framework that too particularly code igniter, Please guide me how to learn from where to learn etc…
shilp says
hi,
i have a query. i just installed codeigniter using composer ( $ composer require “rogeriopradoj/codeigniter 2.2.1-rc.2” ) There i got folder structure on root
-application
-vendor
and system file was in vendor folder. I m quite confused whats the se of this vendor folder. And how to start project . Please help me out
ArunValaven says
Hai Rana.. There is in need to change the code from $list[0] = (object)NULL; to $list[1] = (object)NULL; in its second occurrence in “Create a model topic”. Array index value need to change from “0” to “1” to get escape from error in displaying output. Thanks for your simple and clear explanation about CodeIgniter.
Correct code:
$list[0] = (object)NULL;
$list[0]->title = “first blog title”;
$list[0]->author = “author 1”;
$list[1] = (object)NULL;
$list[1]->title = “second blog title”;
$list[1]->author = “author 2”;
Amandeep Singh says
Thanks sir for this blog
rady says
Hi Mr.Rana
I hope this blog so good for beginner CI like me.
Thank you.
Haseem Mujahidh says
thank you,Highly appreciate if you use file name and paths in your tutorial,then it would be a absolute beginners guide.
mariam says
thank you for this… I will bookmark for the future