I'm implementing a search box using CodeIgniter, but I'm not sure about how I should pass the search parameters through. I have three parameters: the search string; product category; and the sort order. They're all optional. Currently, I'm sending the parameters through $_POST
to a temporary method, which forwards the parameters to the regular URI form. This works fine. I'm using a weird URI format though:
http://site.com/products/search=computer,sort=price,cat=laptop
Does anyone have a better/cleaner format of passing stuff through?
I was thinking of passing it into the products method as arguments, but since the parameters are optional things would get messy. Should I suck it up, and just turn $_GET
methods on? Thanks in advance!
A much better approach, and the method the CI developers intended, is to add all your search parameters to the URI instead of a query string like so:
You would then parse all the URI segments from the 3rd segment ("term") forward into an array of key => value pairs with the
uri_to_assoc($segment)
function from the URI Class.This would give you easy access to all the search parameters and they could be in any order in the URI, just like a traditional query string.
$data->search_params
would now contain an array of your URI segments:Read more about the URI Class here: http://codeigniter.com/user_guide/libraries/uri.html
Query Strings
You can enable query strings in CodeIgniter to allow a more standard search function.
Config.php
Once enabled, you can accept the following in your app:
The benefit here is that the user will find it easy to edit the URL to make a quick change to their search, and your search uses common search functionality.
The down side of this approach is that you are going against one of the design decisions of the CodeIgniter development team. However, my personal opinion is that this is OK provided that query strings are not used for the bulk of your content, only for special cases such as search queries.
If you're using a fixed number of parameters, you can assign a default value to them and send it instead of not sending the parameter at all. For instance
Next, in the controller you can ignore the parameter if (parameter == 'all'.)