Passing multiple variables in URL using codeigniter

僤鯓⒐⒋嵵緔 提交于 2019-11-30 18:20:47

You can use uri to retrieve values in your url

Here is an example

public function getproduct()
{
  $productID =  $this->uri->segment(3);
  $factoryID =  $this->uri->segment(4);
  // ProductID will be 25
  // Factory ID will be 45
}

Then you can just use the values as you please

Donovan

The accepted answer will work for this particular issue, but will not work if the url ever changes. To access multiple variables in your controller, simply add to the function definition.

http://localhost/project/main/getproduct/24/45

class Main extends CI_Controller {

    public function getproduct($productID = 0, $factoryID = 0)
    {
      // ProductID will be 25
      // Factory ID will be 45
    }
}

Reference: CodeIgniter User Guide

Alex7

You must set a route in config/routes.php to parse the items.

It looks like:

   $route["getproduct/(:any)/(:num)"]="main/changequestion/$1/$2"

Then i hope it will work.

If someone else runs into this using CI3. In CodeIgniter 3 no special route is needed. Not sure if it also works on CI2 now.

You can access those URI segments using parameters just like that:

http://localhost/project/main/getproduct/24/45

public function getproduct($productID, $factoryID){
  .....
}

You can use uri to retrieve values in your url http://localhost/project/main/get_product/12/23

Here is an example

public function get_product(){
  $product_id =  $this->uri->segment(3);  // Product id will be 12
  $factory_id =  $this->uri->segment(4);  // Factory id will be 23

}

Then you can just use the values as you please

Faisal

http://example.com/project/main/getproduct/24/45

To get '45', you can do this:

 $id1 =  $this->uri->segment(3);
 echo $id1; //output is 45

Passing URI Segments to your methods

If your URI contains more than two segments they will be passed to your method as parameters.

For example, let’s say you have a URI like this:

example.com/index.php/products/shoes/sandals/123

Your method will be passed URI segments 3 and 4 (“sandals” and “123”):

<?php
class Products extends CI_Controller {

        public function shoes($sandals, $id)
        {
                echo $sandals;
                echo $id;
        }
}

Important!!! If you are using the URI Routing feature, the segments passed to your method will be the re-routed ones.

Refer to this link as Codeigniter Official Guide. Codeigniter Official Guide.

Solution of this problem is using of _remap() function. You just need to add this function before index() function

function _remap($method, $args)
{

       if (method_exists($this, $method))
       {
           $this->$method($args);
       }
       else
       {
            $this->Index($method, $args);
       }
}

I hope this will solve your problem.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!