CodeIgniter Forums
[ASK] About URI Routing - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived General Discussion (https://forum.codeigniter.com/forumdisplay.php?fid=21)
+--- Thread: [ASK] About URI Routing (/showthread.php?tid=31896)



[ASK] About URI Routing - El Forum - 07-06-2010

[eluser]senz[/eluser]
Hi all,

I wanna ask about URI Routing. I just create the simple controller category.php and the code like this :
Code:
<?
class Category extends Controller
{

    function Category()
    {
        parent::Controller();
    }
    
    function index()
    {
        echo "Category";
    }
    
    function first($param_one = '')
    {
        echo $param_one;
    }
    
    function second($param_one = '', $param_two = '')
    {
        echo $param_one." ".$param_two;
    }
}
?>
I wanna pass to 2nd and 3rd parameter in uri segments.
Ex :
1. http://localhost/codeigniter/category/health
2. http://localhost/codeigniter/category/health/stop_smoking
I just edited the routes.php to and the code like this :
Code:
<?
$route['category/(:any)'] = "category/first/$1";
$route['category/(:any)/(:any)'] = "category/second/$1/$2";
?>
When i write in the address bar :
http://localhost/codeigniter/category/health => the result is : health
and when i write :
http://localhost/codeigniter/category/health/stop_smoking => the result is still health and not stop_smoking

My question is how can i pass the 3rd parameter?


[ASK] About URI Routing - El Forum - 07-06-2010

[eluser]mddd[/eluser]
(:any) will match ANYTHING! So if you ask for /category/health/smoking, that url will match the first rule and be rewritten to /category/first/health/smoking.
You should reverse the order of your rules. That way, it is first checked if there is a url with two parts after 'category'. If that is not matched, the rule with one part after 'category' is tried.


[ASK] About URI Routing - El Forum - 07-06-2010

[eluser]senz[/eluser]
Can you explain with the code. Sorry i'm newbie and i didn't get it what you say...
How should i write in routes and controller?...


[ASK] About URI Routing - El Forum - 07-06-2010

[eluser]mddd[/eluser]
The problem is that (:any)/(:any) is a match to "health/smoking", but (:any) also is a match to "health/smoking" !
So, the rule that you put first will match. To get $1 and $2 correct, you must make sure that the rule with (:any)/(:any) is the first one in the file.

Code:
<?
$route['category/(:any)/(:any)'] = "category/second/$1/$2";
$route['category/(:any)'] = "category/first/$1";
?>



[ASK] About URI Routing - El Forum - 07-06-2010

[eluser]senz[/eluser]
It works!!.. Thanks
Smile