You are on page 1of 11

Shwetank Kumar Gupta | shwetankeducation.

com|+91-9815144280

Codeigniter interview questions and answers


For freshers and experienced
Content Ref :pcds.co.in | only for use Education and Job purpose, not for official purpose.

Questions What is codeigniter ?


:1

Answers : Codeigniter is a framework which is mainly focussed on web application development .It is well known
1 for its performance speed.It has inbuilt libraries which helps to build web application

Questions
Who developed codeigniter?
:2
Answers :
Codeigniter was developed bt ellislab Inc.
2

Questions
Why codeigniter is called as loosely based mvc framework?
:3
Answers : advertisements
3
Reason behind this is we does not need to follow strict mvc pattern while creating application.We can
also able to build with model only view and controllers are enough to built a application.

Questions
What are helpers?
:4
Answers : It is a group of functions which helps you to do particular functions. Example there are form helper to
4 create a form .$this->load->helper(form);

Questions
What are hooks in codeigniter?
:5
Answers : Hooks are used to modify the inner functionality of framework without affecting core files.Hooks are
5 present in application/config/hooks.php

Questions
How to insert data into database table in CodeIgniter ?
:6
Answers : Step1 This will be your controller.
6

<?php
class Site extends CI_Controller
{
function index()

{
$this->load->view(form.php);// loading form view
}
function insert()
{

1
Shwetank Kumar Gupta | shwetankeducation.com|+91-9815144280

$this->load->model(site_model);
$this->site_model->insert();
$this->load->view(success.php);//loading success view
}
}

Step 2 This will be your views. Befor creating views go to autoload.php and autoload url helper
and database class. In your config.php set config['base_url'] = path to your site; form.php

<form action=<?php echo base_url();?>Site/insert method=post>


Field 1 <input type = text name=f1><br>
Field 2 <input type = text name=f2><br>
Field 3 <input type = text name=f3><br>
<input type=submit>
</form>

Step 3 success.php
<b>Your data has been inserted!!!</b>

Step 4 In your model you need to pull those datas of form and insert into db this way
site_model.php

<?php
class Site_model extends CI_Model
{
function insert()
{
$f1 = $_POST['f1'];
$f2 = $_POST['f2'];
$f3 = $_POST['f3'];
$this->db->query(INSERT INTO tbl_name VALUES($f1,$f2,$f3));
}
}

There must be some problem with your configuration. To use the process above please set
the following settings. In your application/config/autoload.php => $autoload['libraries'] =
array(database); $autoload['helper'] = array(url); If you have not used htaccess or route
files then in URL place the full URL.

Questions How do I embed views within views? Nested templates? Header, Main, Footer (Blocks)
:7 design? Partials? Page Fragments? Ruby on Rails style Yield functionality?
Answers : There are several other described ways to deal with this problem:
7
Version 1.6 (Released January 31, 2008) has support for multiple views. See the User Guide for more

2
Shwetank Kumar Gupta | shwetankeducation.com|+91-9815144280

to the core makes some of these approaches "old school" (as it


details. That change
were). This forum thread covers some good ground:
http://codeigniter.com/forums/viewthread/87346/

First, basic information on views and the optional third 'return' parameter:
http://www.codeigniter.com/wiki/Displaying_Multiple_Views/ and also, The CI
Loader class documentation page

Coolfactor's View Library is one solution to nesting views in a tidy way.


http://codeigniter.com/forums/viewthread/49910/

Gyorgy Fekete's View library similar to Coolfactor's with the differences spelled out
in the thread. http://codeigniter.com/forums/viewthread/62521/

Another place to get advice if you don't want to add a new library is Rick Ellis'
original thread on the subject (Embedding Views within Views).
http://codeigniter.com/forums/viewthread/44916/

Also, teamhurting has implemented a Ruby On Rails style Yield approach that uses
CI's hooks system: Yield using hooks -
http://codeigniter.com/forums/viewthread/57902/

Another similar approach using a basic class rather than a class as a hook:
http://codeigniter.com/wiki/layout_library/

A thread where esra lists a few threads on this topic:


http://codeigniter.com/forums/viewthread/57965/

A Rails-Style ActionView library and helper called Ocular has a web page wiki here:
http://codeigniter.com/wiki/Ocular_Layout_Library/ and a thread here:
http://codeigniter.com/forums/viewthread/65050/

A thread for a View library (author tested with Matchbox)


http://codeigniter.com/forums/viewthread/67028/

Questions
How to Preparing Database for CodeIgniter ?
:8
Answers : Create a database named "codeigniter" and a table named "hello". We use phpMyAdmin for easy.
8
Open your phpmyadmin.

Enter database name "codeigniter" in create new database field.

Click Create button. Your database will be created.

3
Shwetank Kumar Gupta | shwetankeducation.com|+91-9815144280

Create new table by entering name of new table at create new table field.

Enter number of fields.

Click Go button.

Enter name of field, type, and length

Choose auto increment and check primary key for primary key field.

Click Save button.

Now, we insert data. Click Insert tab.

Enter data.

Click Go for saving.

Questions
How do I pass parameters to a controller\'s index() function?
:9
Answers : The obvious problem is that a second parameter on the URL will be interpreted as the method name.
9
Short answer - use a URL like this: /controller/index/param1/param2

Long answer-
using _remap() you can work some magic. This code is supplied courtesy
of Colin Williams

function _remap ( $method ) {


$param_offset = 2;

// Default to index
if ( ! method_exists($this, $method))
{
// We need one more param
$param_offset = 1;
$method = 'index';
}

// Since all we get is $method, load up everything else in the URI


$params = array_slice($this->uri->rsegment_array(), $param_offset);

// Call the determined method with all params


call_user_func_array(array($this, $method), $params);
}

4
Shwetank Kumar Gupta | shwetankeducation.com|+91-9815144280

Questions
How do I do a COUNT(\'foo\') using the Active Record functions?
: 10
Answers : You need to use the SQL AS feature, where you assign a new name to a piece of data. For example:
10
$this->db->select("COUNT('foo') AS foo_count", FALSE);
// Run your query
Questions
How to Install CodeIgniter ?
: 11
Answers :
11
CodeIgniter is installed in four steps:

Unzip the package.


Upload the CodeIgniter folders and files to your server. Normally the index.php file will be at your root

Open the application/config/config.php file with a text editor and set your base URL. If you
intend to use encryption or sessions, set your encryption key.
If you intend to use a database, open the application/config/database.php file with a text editor
and set your database settings.

If you wish to increase security by hiding the location of your CodeIgniter files you can rename
the system and application folders to something more private. If you do rename them, you must
open your main index.php file and set the $system_folder and $application_folder variables at
the top of the file with the new name you've chosen.

For the best security, both the system and any application folders should be placed above web
root so that they are not directly accessible via a browser. By default, .htaccess files are included
in each folder to help prevent direct access, but it is best to remove them from public access
entirely in case the web server configuration changes or doesn't abide by the .htaccess.

After moving them, open your main index.php file and set the $system_folder and
$application_folder variables, preferably with a full path, e.g. '/www/MyUser/system'.

One additional measure to take in production environments is to disable PHP error reporting and
any other development-only functionality. In CodeIgniter, this can be done by setting the
ENVIRONMENT constant, which is more fully described on the security page.

That's it!

If you're new to CodeIgniter, please read the Getting Started section of the User Guide to begin
learning how to build dynamic PHP applications. Enjoy!

If you wish to increase security by hiding the location of your CodeIgniter files you can rename
the system and application folders to something more private. If you do rename them, you must
open your main index.php file and set the $system_folder and $application_folder variables at
the top of the file with the new name you've chosen.

5
Shwetank Kumar Gupta | shwetankeducation.com|+91-9815144280

For the best security, both the system and any application folders should be placed above web
root so that they are not directly accessible via a browser. By default, .htaccess files are included
in each folder to help prevent direct access, but it is best to remove them from public access
entirely in case the web server configuration changes or doesn't abide by the .htaccess.

After moving them, open your main index.php file and set the $system_folder and
$application_folder variables, preferably with a full path, e.g. '/www/MyUser/system'.

One additional measure to take in production environments is to disable PHP error reporting and
any other development-only functionality. In CodeIgniter, this can be done by setting the
ENVIRONMENT constant, which is more fully described on the security page.

That's it!

If you're new to CodeIgniter, please read the Getting Started section of the User Guide to begin
learning how to build dynamic PHP applications. Enjoy!

Questions
How do I call one Controller\'s methods from a different Controller?
: 12
Answers : Short answer: You don't
12
Wrong answer: Use the $CI = get_instance() trick.

Long answer: You shouldn't actually be trying to do this. It implies that your design isn't quite easy
to re-engineer the relevant bits when you first discover this problem.

It's likely that the method you want to call should simply be relocated - this might
mean moving it into a helper, library, model or your MY_Controller - where it can be
accessed by any number of controllers.

Questions
Can I cache only certain parts of a page?
: 13
Answers : This is related to the question above about nested templates and partials. Basically, CI cache library
13 (1.5.4) only supports full page caching - it's all or nothing. There are several ontributions that can
help.

The Sparks library is one approach. (NOTE: the Sparks object caching library is
currently an orphan (as of 20070925) as the developer has moved on to Zend
Framework - anyone want to step up and carry it on?)

In case you have questions to ask on the forum, please review this general information
on caches. There are many levels of caching and they can be broken down into a few
categories and approaches:

PHP code itself: php opcode of some kind

6
Shwetank Kumar Gupta | shwetankeducation.com|+91-9815144280

The following can be classed as session-specific or global caches depending on the


approach: DB cache: db query, db object serialization HTML output cache: partial or
full page caching

Browser cache is always (by definition) session-specific: Browser cache: using


headers to control cache, JS and CSS architecture to optimize browser cache-ability

Questions
Can I extend the core Database class?
: 14
Answers : No, you can not. This is quite explicitly described in the Creating Libraries section of the user guide:
14 [quote]

The Database classes can not be extended or replaced with your own classes, nor can the Loader
class in PHP 4. All other classes are able to be replaced/extended.

[/quote]

Questions
How do I call methods in one controller via another controller?
: 15
Answers : Often this question disguises a requirement for some shared methods - consult the earlier question on
15 **View Partials* and Header/Footer/Menu common views first, and confirm your question isn't better
answered there
Questions
How do I find out the ID of the row I just inserted?
: 16
Answers : (Just so that people searching for this will be more likely to find it, we'll mention that this is
16 comparable to the native PHP mysql_insert_id() function.)

$foo = $this->db->insert_id();
Questions
How do I see the actual raw SQL query generated by CI\'s Active Record
: 17
Answers : You can do this before your query:
17
$this->db->_compile_select();

.. and then this, once you've run the query:

$this->db->last_query();
Questions
How to Create Application at CodeIgniter ?
: 18
Answers : First, we make controller, create a file name "hello.php" within: \system\application\controllers. Enter
18 following code:

Next step, make a view. Create you_view.php within CodeIgnitersystemapplicationviews.


Enter just simple line code like:
1 Hello, you!

7
Shwetank Kumar Gupta | shwetankeducation.com|+91-9815144280

Now, test your application. Point your browser to


http://localhost/CodeIgniter/index.php/Hello/you You should get like this:

Questions
How to Install CodeIgniter Framemwork
: 19
Answers : CodeIgniter Step By Step Tutorial: After understand about codeIgniter at this, now, we learn how to
19 install CodeIgniter. We will install to our local computer. Before follow this instruction please
download CodeIgniter at www.codeigniter.com.

Open your root web server.

Put CodeIgniter downloaded.

Extract it, you will get a folder named "codeigniter_[version]".

For simple, rename the folder to be "CodeIgniter" only.

Now, open config.php within CodeIgnitersystemapplicationconfig.

Change base site url at line 14:

Point your browser to http://localhost/CodeIgniter.

Questions I keep repeating lumps of code - things like login-dialogs, stylesheets, headers, footers, or
: 20 menus - is there some place I can define them just once?
Answers : this is also covered by the next section (on nested templates, view partials etc) which in turn contains
20 many links into the forums - this will provide a wealth of alternative approaches.

It is also asked frequently (hence its presence here - duh!) on the forums -- about once
every 36 hours on average, usually prefaced with the lie 'I couldn't find anything
about how to do this...'. You're advised (read strongly encouraged) to use the forum
search feature and Search in Titles Only for the words 'header' and 'footer

Questions
Is there a way to cycle $this->input->post() items?
: 21
Answers : There are no CodeIgniter functions to do this, but you can accomplish this easily with a construct such
21 as this one. The result of this function is a $safe_post_array that contains all posted data that has
passed your own Input Class rules.

foreach (array_keys($_POST) as $key) {


$safe_post_array[$key] = $this->input->post($key);
}

8
Shwetank Kumar Gupta | shwetankeducation.com|+91-9815144280

You can also do something neat like this, if you want to pull all the data out of
$_POST into your own array, cleaning it as it comes across:

$data['fields'] = xss_clean($_POST);

Questions
Tell me the Setting Database Configuration
: 22
Answers : open database.php within CodeIgniter\system\application\config. Set config
22 Make sure, it match with your database.
Questions
How do I migrate my existing \'normal\' PHP site to CodeIgniter?
: 23
Answers : Put the whole site in a subfolder of your root web folder, and use .htaccess to rewrite all requests to
23 the subfolder (we named it oldsite but any name will do). Be wary of absolute file paths
(do a find on the entire codebase to look for any file that uses the filesystem). Make
sure everything works before you continue any further.

Now setup your CI site in the root of the webfolder. Make sure the .htaccess still
routes all traffic to the old site.

Now overwrite the Router class with a MY_Router. Let CI check if there is a
controller present which matches against the url (the way it normally does). If not,
redirect to the oldsite folder. Remove the .htaccess rule that redirects all traffic to the
old site.

Now every request will go through the CI index.php. The Router Class will test if a
controller exists for the requested url. (just like it would normally so you can user
your routes in your config folder). If it won t find one, normally CI would return
a 404. Instead it now redirects the request to the old site.

Now you can slowly migrate parts of the website. Since the CI controllers take
precedent over the old website, you can slowly replace parts of the old websites, and
add new features as you would a normal CI site.

One word of caution. This will seriously impact any pagerank google has given to
your website, since google doesnt like redirects. To counter this you can use your
.htaccess to rewrite old urls to the oldsite subfolder, although the list could
become quite large.

Questions
Is CodeIgniter uses a functions and names in its operation?
: 24
Answers : CodeIgniter uses a series of functions and names in its operation. Because of this, some names
24 cannot be used by a developer. Following is a list of reserved names that cannot be used Controller
names

Since your controller classes will extend the main application controller you must be
careful not to name your functions identically to the ones used by that class, otherwise

9
Shwetank Kumar Gupta | shwetankeducation.com|+91-9815144280

your local functions will override them. The following is a list of reserved names. Do
not name your controller any of these:

Controller
CI_Base
_ci_initialize
Default
index

Functions

is_really_writable()
load_class()
get_config()
config_item()
show_error()
show_404()
log_message()
_exception_handler()
get_instance()

Variables

$config
$mimes
$lang

Constants

ENVIRONMENT
EXT
FCPATH
SELF
BASEPATH
APPPATH
CI_VERSION
FILE_READ_MODE
FILE_WRITE_MODE
DIR_READ_MODE
DIR_WRITE_MODE
FOPEN_READ
FOPEN_READ_WRITE
FOPEN_WRITE_CREATE_DESTRUCTIVE
FOPEN_READ_WRITE_CREATE_DESTRUCTIVE
FOPEN_WRITE_CREATE
FOPEN_READ_WRITE_CREATE

10
Shwetank Kumar Gupta | shwetankeducation.com|+91-9815144280

FOPEN_WRITE_CREATE_STRICT
FOPEN_READ_WRITE_CREATE_STRICT

Questions
How do I call one Model\'s methods from a different Model?
: 25
Answers : Short answer: You don't
25
Long answer: You shouldn't actually be trying to do this. It implies that your design isn't quite right.
mplies that it's not (also, if you have to
(Your design may be right - I'm just saying that this
ask this question, this also suggests you probably shouldn't be doing this.)) Consider
moving things around such that MY_Model or a library or helper contains the
functionality you're trying to utilise in this way.

If you absolutely positively have to do this (and remember - you shouldn't) you can do
the old $CI = get_instance() trick. Phil explains it in this thread but loosely it is
simply this:

$ci =& get_instance();


$ci->load->model('Mymodel');
$ci->mymodel->mymethod();

11

You might also like