-
Notifications
You must be signed in to change notification settings - Fork 0
Table of Contents (Absent an automagic ToC feature in the CI-wiki, this is here for convenience only. Do NOT assume all the FAQs on this page are listed in this table of contents -- please read through this whole page, just in case. Ctrl-F is your friend ;)
Database
- Be sure to also check the SQL FAQ page.
- How do I see the actual raw SQL query generated by CI's Active Record
- How do I find out the ID of the row I just inserted?
- How do I do a COUNT('foo') using the Active Record functions?
- Can I extend the core Database class?
- Oracle does weird things
Design
- 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?
- How do I embed views within views? Nested templates? Header, Main, Footer (Blocks) design? Partials? Page Fragments? Ruby on Rails style Yield functionality?
- How do I pass parameters to a controller's index() function?
- How do I call one Controller's methods from a different Controller?
- How do I call one Model's methods from a different Model?
Errors
- Headers already sent
Forms and Input and POST data
- Is there a way to get all the $this->input->post() items?
Images
- When I load an image in my code, it doesn't appear on the rendered page?
JavaScript and AJAX and JS libraries
- I'm confused
Site migrations, relocations and platform differences
- After moving from development to production, my site stopped working
- How do I migrate my existing 'normal' PHP site to CodeIgniter?
Tables
- I want to do {$SOMETHING_TRICKY} with a Table
CodeIgniter and EllisLab and ExpressionEngine
- When is the next version of CodeIgniter coming out? What can I expect from the next version of CodeIgniter?
- I've got cool new code for CI. What is the process for getting it included in the official CI distribution?
Plain old frequently asked questions
- How do I find the name of the current controller and/or method?
- *Can I cache only certain parts of a page? *
- How do I call methods in one controller via another controller?
Checking under the hood of queries, that kind of thing
===> Be sure to also check the SQL FAQ page. <===
Answer 1 Turn on profiling (part of the benchmarking class) - this will show the full detail of all the SQL queries for the page.
Answer 2 You can do this before your query:
$this->db->_compile_select();
.. and then this, once you've run the query:
$this->db->last_query();
(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.)
This is covered in the Query Helper Functions section of the CI User Guide - the function you're looking for is:
$foo = $this->db->insert_id();
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, and then use the foo_count variable.
Refer to the CI User Manual's section on Active Record Class for more information.
Answer 1 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]
Answer 2 Yes, you can, using the method described by rafsoaken
Yes, this seems to be kind of known, though so few CI users are on Oracle that it's hard to pin down the problem.
Have a read of this thread, especially if you're seeing an off-by-one error on row counts.
This thread relates to CI 1.7.0 and Oracle versions 9 & 10 - not being able to connect to the database from within CI.
There are some other Known Issues with Oracle documented on this wiki.
Architecture of your application, what goes where, design patterns, that kind of thing
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?
Short answer - you probably want to extend the core Controller, so do a search in the forums for 'MY_Controller', or check out the section covering this on the different Approaches Guide page. This works well when you want to seamlessly introduce data into the CI superobject ($this-> ...).
Less short answer - in very general terms, if you want to call a function that doesn't require access to the CI superobject, then you probably want a Helper (and you probably want to autoload it). If you want some functions that needs database access to a small number of tables, and is likely to be used through many controllers, you might be best with an autoloaded Model.
Longer answer - 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'.
Asking this question anew within the forums is likely to imbue a certain degree of chagrin.
How do I embed views within views? Nested templates? Header, Main, Footer (Blocks) design? Partials? Page Fragments? Ruby on Rails style Yield functionality?
Check out the Different Approaches Guide to this problem.
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 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/
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);
}
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 right, but on the upside it's 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. You're encouraged to consult the user guide regarding helpers v. libraries, and elsewhere on this page and wiki for information about MY_Controller.
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 implies 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();
Frequently Seen Error messages, that kind of thing
9 times out of 10, this error is caused by one of:
- whitespace after a closing ?> tag,
- whitespace before a <?php opening tag at the start of one of your files
- residual debugging echo (print_r, var_dump, etc) in your non-view files
The solution(s) are easy - do not use closing ?> tags anywhere, ever, in your libraries, models, controllers and helpers. Check those files for any whitespace at the start of the file. Check for echo/print_r/var_dump/etc functions - usually you'll see the output of those on-screen before the error message, in any case.
Handling incoming form data, ->input->post .v. $_POST, that kind of thing
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);
}
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);
Embedding graphic images, that kind of thing
This is a hugely common problem, and 99 times out of ten it's because you are confused about paths. This is very much a PHP / HTML problem, not a CodeIgniter one, but the following hints might help you resolve this.
First - look at the page source in your browser - this is themost important and most useful thingyou can examine. It'll give you very strong hints immediately as to what's going wrong. You can cut-n-paste the img src component into another browser, and then start modifying it until you find a path that works.
Second - utilise the CI helpers, if you're not already. For example, if you keep your images at**/assets/imagesthen you can pullfoo.jpg**in with this code (modify to taste) in your view:
<?php
$foovar = "foo.jpg";
$img_array = array ("src"=> "/assets/images/". $foovar, "border"=>"0");
echo anchor (img($img_array));
?>
I'm confused
Yes, but you needn't be.
JS / AJAX works the same in CI as it does in conventional PHP - you still need to write your JS, ship it out, have URL's that can respond sensibly to JS queries and the like.
Do a search on the Intergoogle for some tutorials - there are bucketloads of the things out there.
For example, this page shows 9 ways to integrate AJAX with CodeIgniter (assuming the link is still alive).
A neat trick suggested by eoinmcg is to put this function into your MY_Controller:
function _is_ajax()
{
return (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest'));
}
You can then call $this->_is_ajax() in your controllers if you want different courses of action based on the type of query for that particular method.
There are a couple of CodeIgniter wrappers or libraries for simplifying (or at least standardising) the way you implement Java_Script: o Carabiner, by tonydewan o External library by darkhouse
Relocating from GNU/Linux to Windows, changing databases engines, that kind of thing
There are several sub-categories to this problem, depending what you mean by 'doesn't work'[/h4]
Please note that you should have done ALL of the following easy steps before posting to the forums: o use phpinfo.php and confirm mod_rewrite is available o cycled through the $config['uri_protocol'] options - trying ALL of the FIVE choices there o checked / changed your .htaccess for host-specific paths o confirmed your PHP versions (CI doesn't care whether you use PHP4 or PHP5 - but it's quite likely that the code you've written does)
[u]Subcategory[/u] - my index.php isn't being hidden anymore If your .htaccess mod_rewrite is no longer working -- check that you have AllowOverride All in your host's config file for the public web directory of your website.
[u]Subcategory[/u] - my library/model/etc isn't loading/running/etc If this has bitten you as you've gone from MS-Windows to a GNU/Linux platform, please verify the case of your libraries and models. Note this is not a bug with GNU/Linux - rather an unfortunate side effect of NTFS being case-insensitive and consequently hiding any failure to abide by the documented standards for class and file names.
Consult the user guide for specifics, but briefly - Controller and Model classes should be a capitalised (first character only) with file names entirely lower case. Library classes are capitalised (first character only) with file names capitalised similarly. Core class extensions start with MY_ (unless you've changed the prefix in config.php) for both filename and class name.
Answer 1 - provided by n0xie How we migrated a rather big site:
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.
Answer 2 provided by sophistry[/b] The Site Migrate wiki page provides a controller that lets you "drop in" an entire existing web site. Just place it in your "views" directory and CI can serve it up just like before (this can even be accomplished with no URI changes). No messing around with .htaccess and redirects. Uses CI's _remap() function.
Generating HTML tables, that kind of thing
The HTML Table Class is a convenient way of generating HTML tables quickly and easily. However it does have its shortcomings, and consequently there are regular questions in the Forums about how to introduce dynamic href links into rows, implementing special CSS markup, and so on.
Because of this - and also because generating HTML within the Controller goes a little against the usual MVC separation of responsibilities - most of the cool kids will recommend that you write your own view partial that generates your
...Release schedules, contributions, that kind of thing
When is the next version of CodeIgniter coming out? What can I expect from the next version of CodeIgniter?
CodeIgniter is a product of EllisLab. New releases and new features in the framework are made available when it is possible to release them, and may always be a surprise: http://codeigniter.com/forums/viewthread/53619/P15/#262381
You can glean some insight from reading the Changelog, which shows the historical frequency of releases and the types and scale of changes.
I've got cool new code for CI. What is the process for getting it included in the official CI distribution?
New code is welcome, but not all code can be included. To maximize the chances of your code making it into CI, test (PHP 4 and 5) and document the code. All decisions about incorporating it fall to EllisLab. Basically, if you want to satisfy your lust for abiding fame you have to make an effort to promulgate your code to as many CI developers as possible who put it through an informal 'vetting' process. As part of this process you should create a 'manual page' to help people learn.
Almost a 'misc' category, but categorically not a dumping ground - these are simply uncategorised questions ... for things that aren't any obvious or particular kind of thing yet
There are standard PHP function that's good for this kind of thing, and you're encouraged to consult the PHP User Guide.
get_class() will return the current class's name.
get_class_methods() will return the full list of methods for a given class.
Alternatively, consult the URI Class in the user manual, paying particular attention to the rsegment() function - as you may be happy with pulling segment(1) for your class, and segment(2) for your method.
Alternatively, you can query the CI Routing class directly, using these functions:
$this->router->class;
$this->router->method;
A. 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 contributions 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
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
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.
Modular Extensions (ME) aka the HMVC library allows you to do this. ME/HMVCYou don't. See http://codeigniter.com/forums/viewthread/55212/ for more discussion.