Ahmar Arshad
Ahmar Arshad

Reputation: 497

Codeigniter Logic for passing function parameters from URL segments

Lets say we have following url, http://www.example.com/controllerName/methodName/param1/param2/param3 In above url param1, param2, param3 are parameters which will be passed to controller method 'methodName'.

Now I just want to know the logic behind to pass function parameters from url and

the second thing is How to map the number of parameter segments from url with controller method arguments like codeigniter?

Upvotes: 0

Views: 2483

Answers (2)

rbcastro17
rbcastro17

Reputation: 197

Codeigniter has an autoloaded uri helper and you can use it in the controller as $this->uri->segment(/*segment #*/) now uri segment is start with the segment 1 which is the controller (the $this->uri->segment(1)), the second is the method of your controller (the $this->uri->segment(2)) the third is the value you want to send to the method (the $this->uri->segment(1)). you can pass as many segment as you want. you can count it with the / seperation. ex. http://localhost/ci/controller(1)/method(2)/value1(3)/value2(4)/value3(5)/valueb(n)

Upvotes: 0

umefarooq
umefarooq

Reputation: 4574

if you have limited number of parameters like 3 or 4 than you can mapped them from routes to controller method like

$route['controllerName/methodName/(:any)/(:any)/(:any)'] = 'controllerName/methodName/$1/$2/$3';

Now you controller method can accept 3 parameters

function methodName($param1,$param2,$param3) {
   echo $param1,' ',$param2,' ',$param3;
}

if number of parameters is long than uri class can help you to fetch all parameters and your route should be smart to send all parameter to that controller method like this

$route['controllerName/methodName/(.+)'] = 'controllerName/methodName';

controller method be like

function methodName(){
   //you will get all segments in an array
   $segments = $this->uri->segment_array();

   //get just one segment
   $segment = $this->uri->segment(1);

}

for more information read uri class and routing documentation

https://www.codeigniter.com/user_guide/libraries/uri.html https://www.codeigniter.com/user_guide/general/routing.html

Upvotes: 0

Related Questions