Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing multiple variables in URL using codeigniter

sorry to bother but I was hoping someone could help me out with a quite mundane issue that I am having within CI. I am able to send a variable via the URL using CI's examples eg:

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

within the getproduct() method of my main controller I can get the variable sent 24, without an issue.

however I now want to pass two variables via the URL, but I have no idea how to do this or whether CodeIgniter will allow me to do this. could someone please show me how to pass 2 variables in CI and a method that can retrieve them I have tried:

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

and then within my getproduct method:

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

but I'm finding my method can get the first variable without an issue but not the second variable. Could anyone point me in the right direction please. Many thanks in advance.

like image 613
TotalNewbie Avatar asked Mar 31 '14 15:03

TotalNewbie


5 Answers

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

like image 63
Donovan Avatar answered Oct 21 '22 22:10

Donovan


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

like image 25
Chitowns24 Avatar answered Oct 21 '22 22:10

Chitowns24


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.

like image 11
Alex7 Avatar answered Oct 21 '22 23:10

Alex7


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){
  .....
}
like image 4
Firze Avatar answered Oct 21 '22 21:10

Firze


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

like image 2
Sani Kamal Avatar answered Oct 21 '22 21:10

Sani Kamal