Wednesday, September 19, 2012

Query String in Code Igniter

| 1 comments
What is a query string?
Defining variables explicitly in the address bar is called query string. For example, http://localhost/blanc/test/shoes?size=42. The string ‘?size=42’ is a query string. Variable name is ‘size’, and the value is 42. This will be retrived in PHP :
$sizeFromQueryString = $_GET[‘size’]; 
So, the value of $sizeFromQueryString will be 42.
Code igniter (I use version 1.7.3) does not support query string by default. You can enable query string for the whole class or just implementing in certain class/controller. Follow the instructions below.

This will involve 2 files only :
A controller that use a query string and the config file (application/config/config.php)
Assume we have a controller named test.

A. Enable Query String for whole class/application
To do this, you just need to modify the config file.
1. Set $config['uri_protocol'] = "PATH_INFO";
2. Then set $config['enable_query_strings'] ="TRUE";
These settings will make query strings enable for the whole application.

B. Enable Query String for a certain controller

I don’t like to use a query string, but when I use autocomplete jquery, it force me to use it, otherwise, I will need to modify the javascript library, so I chose to enable query string just in a certain controller. Follow the steps below:
1.  Set $config['uri_protocol'] = "PATH_INFO"; 
2.  Set $config['enable_query_strings'] ="FALSE"; 
3. in the controller we want query string to be enabled, add this line:
parse_str($_SERVER['QUERY_STRING'],$_GET);
in the controller’s constructor function. See the image below.
enable query string locally
enable query string locally
Go to the function shoes and test whether query string is enabled by typing echo $_GET[‘size’];
Go to the browser and type the address http://localhost/xxxxxxx/test/shoes?size=42.
If the query string disabled, the page will display as below.
query string is disabled


If the 42 displayed, then the query string is enabled.
query string is enabled


I was using this query string feature when I need to use jquery autocomplete. The javascript method points to a link that uses a query string, and I prefer to create a custom code in the PHP section than change the javascript library.

Hope this post useful. 

1 comment: