
I have already written few articles on codeigniter, however, didn’t written for the 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 to the developers who are absolute beginners on codeigniter and want to have a better start very quickly.
Prerequisites:
However, prior using codeigntier, its required that you know what mvc design pattern is. To more about mvc, you can start with the wiki article on mvc .
Also, wish you have already xampp/wamp or something similar already set up in 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 won’t never going to work on this folder our selves ever. All our codes are going to take place in the ‘application directory’. There you will see a list of sub directories as like the following image:
Lets get a little familiar with the directories:
- Cache : This directory will contain all kinds of cached files if you are using so. However, you will may need to provide write access for the application to this directory as codeigniter will need to create temporary files on this folder. To know how to use caching, please refer to 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 know more, please visit codeigniter documentation about using config class .
- Controller : This directory includes all controller definitions. It can be said as the entry point of application also, every requests triggers a certain method of a controller.
- Core : If we need to extend the functionality of any core classes like controller,loader,router etc, then we can declare new class here which will extend those core classes and put the implementation inside those.
- Errors : This directory includes some basic template for showing various kind of errors like db error, 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 declaration. 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 log for debug/error/info, please 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, which are imported from third-party. So, difference between the ‘third_party’ and ‘libraries’ is that, one is for self-made libraries, for app specific, other one 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 know more in details, please refer to the codeigniter url structure documentation .
Create A Basic Controller:
Lets 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 */
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’ the default method that is being executed when no other method is specified in url. And we understood one thing clearly, to create a page, we may ignore to have a model and/or a view file, but we must need a controller.
Create a model :
Lets create a simple model on our application. We won’t cover any database activity on this tutorial. But, its pretty easy. setup your database server info on the ‘config/database.php’. Then you can access database in either straight cut way or use codeigniter provided ‘active record’ library that helps a lot creating/executing SQL query easily. You can read more on my another article about codeigniter active record class. 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; } } ?>
Modify The Controller:
To use the data from model, lets change our controller code that will receive data from 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); } }
Create A View:
Lets 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>
Calling a view from controller:
The above “Modify The Controller” already demonstrates how to call a view. However there are 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. Just, 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");
Notice that, we haven’t use any extension(here .php) for the template name as it recognize it automatically.
Another important thing to remember is that, the second parameter is optional to call the view. If you have any data to pass to view, then pass it through the second parameter. If you haven’t, then you won’t have to pass any second parameter at all.
Also, data that are passed to view are parsed from associated array. Lets say, we are assigning and passing some data from 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); } }
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>
Notice that, every associative key from $data becomes as a variable on the view section. So, 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, best place to know in details is the codeigniter documentation. There you will find in details about every thing with examples also. I found it as one of the best documentation on web. You can ask any kind of question related to codeigniter on their official forum.
Also don’t forget to checkout my codeigniter tutorials series for detailed tutorial with example on various specific areas of this popular framework! Happy coding 🙂
First example works but the rest of the examples are lacking file names, etc. so not of much use as a beginner tutorial.
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..
Thanks for this…Like it
Nice One. Thanks..
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.
How to create new controller.
Hi, Please refer to “Create A Basic Controller” section. Please let me know f you don’t understand anything..
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.
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 http://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.
that’s good
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?
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.
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!
Wow, nice post buddy. It can help me to develop website using codeigniter framework.
thank you very much
it give me complete inside out to the MVC as well as codeignighter
thanks you very very much
this helped me a lot buddy and moreover your site interface is really good and CLEAN.
keep up the good work.
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.
try using:
APPPATH.”/include_folder/file_name.php”
it vary good for fresher + inretmideate
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
Thanx Rana for providing these Tuts these are very useful for everyone especially fresher
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
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.
what would be the best IDE for code igniter?
where I can use breakpoints,
the first program for blog.. throws an error more of a warnin. creating default object on empty value..
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.
How to configure with lamp? Anyone please help me..
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
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.
Good explanation..but lacks screenshots.
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.
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
That is because of php version, I assume. Should be fixed by using ‘$list = (object)NULL;’ . Hope this helps.
Excellent Tutorial !! Helps alot.
Good and understandable tutorial
Thanks for tutorial 🙂
so nice
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!
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.
nice tutorials.. thanks Mr.Rana
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
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.
Please tell me how we load multiple pages in ci
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…
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
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”;
Thanks sir for this blog
Hi Mr.Rana
I hope this blog so good for beginner CI like me.
Thank you.
thank you,Highly appreciate if you use file name and paths in your tutorial,then it would be a absolute beginners guide.
thank you for this… I will bookmark for the future