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. : 1 1 What is codeigniter? Codeigniter is a framework which is mainly focussed on web application development.it is well known for its performance speed.it has inbuilt libraries which helps to build web application : 2 2 Who developed codeigniter? Codeigniter was developed bt ellislab Inc. : 3 3 Why codeigniter is called as loosely based mvc framework? advertisements 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. : 4 4 What are helpers? It is a group of functions which helps you to do particular functions. Example there are form helper to create a form.$this->load->helper( form ); : 5 5 What are hooks in codeigniter? Hooks are used to modify the inner functionality of framework without affecting core files.hooks are present in application/config/hooks.php : 6 6 How to insert data into database table in CodeIgniter? Step1 This will be your controller. <?php class Site extends CI_Controller function index() $this->load->view( form.php );// loading form view function insert() 1
$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. : 7 7 How do I embed views within views? Nested templates? Header, Main, Footer (Blocks) design? Partials? Page Fragments? Ruby on Rails style Yield functionality? There are several other described ways to deal with this problem: Version 1.6 (Released January 31, 2008) has support for multiple views. See the User Guide for more 2
details. That change to the core makes some of these approaches "old school" (as it 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/ : 8 8 How to Preparing Database for CodeIgniter? Create a database named "codeigniter" and a table named "hello". We use phpmyadmin for easy. Open your phpmyadmin. Enter database name "codeigniter" in create new database field. Click Create button. Your database will be created. 3
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. : 9 9 How do I pass parameters to a controller\'s index() function? The obvious problem is that a second parameter on the URL will be interpreted as the method name. 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
: 10 10 : 11 11 How do I do a COUNT(\'foo\') using the Active Record functions? You need to use the SQL AS feature, where you assign a new name to a piece of data. For example: $this->db->select("count('foo') AS foo_count", FALSE); // Run your query How to Install CodeIgniter? 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
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! : 12 12 How do I call one Controller\'s methods from a different Controller? Short answer: You don't 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. : 13 13 Can I cache only certain parts of a page? This is related to the question above about nested templates and partials. Basically, CI cache library (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
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 : 14 14 Can I extend the core Database class? No, you can not. This is quite explicitly described in the Creating Libraries section of the user guide: [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] : 15 15 : 16 16 How do I call methods in one controller via another controller? Often this question disguises a requirement for some shared methods - consult the earlier question on **View Partials* and Header/Footer/Menu common views first, and confirm your question isn't better answered there How do I find out the ID of the row I just inserted? (Just so that people searching for this will be more likely to find it, we'll mention that this is comparable to the native PHP mysql_insert_id() function.) $foo = $this->db->insert_id(); : 17 17 How do I see the actual raw SQL query generated by CI\'s Active Record You can do this before your query: $this->db->_compile_select();.. and then this, once you've run the query: : 18 18 $this->db->last_query(); How to Create Application at CodeIgniter? First, we make controller, create a file name "hello.php" within: \system\application\controllers. Enter following code: Next step, make a view. Create you_view.php within CodeIgnitersystemapplicationviews. Enter just simple line code like: 1 Hello, you! 7
Now, test your application. Point your browser to http://localhost/codeigniter/index.php/hello/you You should get like this: : 19 19 How to Install CodeIgniter Framemwork CodeIgniter Step By Step Tutorial: After understand about codeigniter at this, now, we learn how to 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. : 20 20 I keep repeating lumps of code - things like login-dialogs, stylesheets, headers, footers, or menus - is there some place I can define them just once? this is also covered by the next section (on nested templates, view partials etc) which in turn contains 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 : 21 21 Is there a way to cycle $this->input->post() items? There are no CodeIgniter functions to do this, but you can accomplish this easily with a construct such 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
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); : 22 22 : 23 23 Tell me the Setting Database Configuration open database.php within CodeIgniter\system\application\config. Set config Make sure, it match with your database. How do I migrate my existing \'normal\' PHP site to CodeIgniter? Put the whole site in a subfolder of your root web folder, and use.htaccess to rewrite all requests to 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 doesnâ t 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. : 24 24 9 Is CodeIgniter uses a functions and names in its operation? CodeIgniter uses a series of functions and names in its operation. Because of this, some names 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
10 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
FOPEN_WRITE_CREATE_STRICT FOPEN_READ_WRITE_CREATE_STRICT : 25 25 How do I call one Model\'s methods from a different Model? Short answer: You don't Long answer: You shouldn't actually be trying to do this. It implies that your design isn't quite right. (Your design may be right - I'm just saying that this mplies that it's not (also, if you have to 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